<?php
namespace App\Http\Services;

use App\Http\Model\SystemConfig;
use App\Http\Model\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Lib\Publisher;
use App\Http\Model\Hint;
use App\Http\Services\UserServices;
use App\Http\Services\GiftServices;
use App\Http\Services\RoomMsgServices;
use App\Http\Services\MsgServices;
use App\Http\Services\RoomTallyServices;
use App\Http\Services\FinanceServices;
use App\Http\Services\RoomServicesInit;
use App\Http\Services\GameServices;
use App\Http\Services\UserFilterServices;
use App\Http\Model\Gift;
use App\Http\Model\GiftBag;
use App\Http\Model\Room;
use App\Http\Model\FinanceRoomWealth;
use App\Http\Model\FinanceWealth;
use App\Http\Model\FinanceCharm;
use App\Http\Model\FinanceKk;
use App\Http\Model\Union;
use App\Http\Model\FinanceUserWallet;
use App\Http\Model\FinanceDiamond;
use App\Http\Services\ThinkingdataServices;
use App\Http\Model\Ad as AdModel;
use App\Http\Model\RoomUser;
use App\Http\Model\ColorGift;
use App\Http\Model\ColorGiftRateConfig;
use App\Http\Model\RoomHot;
use App\Http\Model\RoomMicro;
use App\Http\Model\Mall;


class SendGiftServices extends CommonServices
{
    protected $ratioConf;// 支付比例
    protected $descConf;// 描述文案
    protected $systemConfigModel;
    private $userService;
    private $giftService;
    private $gameService;
    private $financeService;
    private $roomMsgService;
    private $msgService;
    private $roomTallyService;
    private $roommicro_service;
    private $roomhostmicro_service;

    private $giftModel;
    private $giftBagModel;
    protected $roomModel;
    private $unionModel;
    private $financeRoomWealthModel;
    private $financeWealthModel;
    private $financeCharmModel;
    private $financeKk_Model;
    private $walletModel;
    private $diamondModel;
    private $crossRoomService;
    protected $tdService;
    protected $userFilterService;
    protected $roomProtectServices;
    protected $adModel;
    protected $roomUserModel;
    protected $colorGiftServices;//新版彩蛋逻辑
    protected $colorGiftModel;
    protected $colorGiftRateModel;
    protected $roomHotModel;
    protected $roomMicroModel;//普通麦
    protected $mallModel;//商品
    protected $model_user;

    //主播收礼实时榜单
    protected $anchorAcceptGiftTimeRankKey = 'ANCHORACCEPTGIFT:TIMERANK:';//zset ANCHORACCEPTGIFT:TIMERANK:{user_id} => {积分}=>{user_id}
    //主播收礼每日榜单
    protected $anchorAcceptGiftDayRankKey = 'ANCHORACCEPTGIFT:DAYRANK:';//zset ANCHORACCEPTGIFT:DAYRANK:{user_id}:{day} => {积分}=>{user_id}

    //用户banner缓存
    protected $userBannerKey = 'USERBANNER:';//string USERBANNER:{userId}:{type} => {string}
    protected $colorGiftMqKey = 'COLOR:MQ:DATA:';//string mq送礼数据 COLOR:MQ:DATA:md5 => {json}
    protected $roomHotKey = 'ROOMHOT:';//string ROOMHOT:{room_id} => {num}

    //拍拍房记录缓存
    protected $roomPaiPaiKey = 'ROOMPAIPAI:LOG:';//string ROOMPAIPAI:LOG:{roomId} => {string}
    //拍拍房收礼送礼用户排行缓存
    protected $roomPaiPaiUserRankKey = 'ROOMPAIPAI:USERRANK:';//zset ROOMPAIPAI:USERRANK:{logId}:{toUserId} => {积分}=>{fromUserId}

    protected $treatedLuckGiftStreamMaxId = 'LUCK:GIFT:STREAM:TREATED:ID';

    public function __construct()
    {
        $this->ratioConf = config('pay.wallet_change_ratio');
        $this->descConf = config('pay.wallet_change_desc');
        $this->systemConfigModel = new SystemConfig();
        $this->userService = new UserServices();
        $this->giftService = new GiftServices();
        $this->gameService = new GameServices();
        $this->financeService = new FinanceServices();
        $this->roomMsgService = new RoomMsgServices();
        $this->msgService = new MsgServices();
        $this->roomTallyService = new RoomTallyServices();
        $this->userFilterService = new UserFilterServices();

        $this->giftModel = new Gift();
        $this->giftBagModel = new GiftBag();
        $this->roomModel = new Room();
        $this->unionModel = new Union();
        $this->financeRoomWealthModel = new FinanceRoomWealth();
        $this->financeWealthModel = new FinanceWealth();
        $this->financeCharmModel = new FinanceCharm();
        $this->financeKk_Model = new FinanceKk();
        $this->walletModel = new FinanceUserWallet();
        $this->diamondModel = new FinanceDiamond();
        $this->crossRoomService = new CrossRoomPkService();
        $this->tdService = new ThinkingdataServices();
        $this->roomProtectServices = new RoomProtectServices();
        $this->adModel = new AdModel();
        $this->roomUserModel = new RoomUser();

        $this->colorGiftServices = new ColorGiftServices();
        $this->colorGiftModel = new ColorGift();
        $this->colorGiftRateModel = new ColorGiftRateConfig();
        $this->roomHotModel = new RoomHot();
        $this->roomMicroModel = new RoomMicro();
        $this->mallModel = new Mall();
        $this->model_user = new User();

    }

    /**
     * 背包赠送礼物
     */
    public function sendGiftByBag($fromUserId, $toUserIds, $giftId, $giftNum, $roomId, $abnormal=0) {
        $result = [
            'code' => Hint::ERROR,
            'message' => '',
            'data' => [],
        ];
        $now = time();
        do {
            $placeType = 2;//礼物来源 1=购买 2=背包
            $giftData = [];//礼物信息
            $roomInfo = [];//房间信息
            $is_certified = 0;//房间是否认证
            //房间信息
            if($roomId > 0) {
                $roomInfo = $this->roomModel->get_room($roomId);
                if(empty($roomInfo)) {
                    $result['code'] = Hint::PARAM_ERROR;
                    $result['message'] = '房间不存在';
                    break;  
                }
                $is_certified = $roomInfo['certified'];
            }
            //校验基本参数
            $check = $this->checkParam($fromUserId, $toUserIds, $giftId, $giftNum, $roomId);
            if($check['code'] != Hint::SUCCESS) {
                $result = $check;
                break;
            }
            //校验收礼用户账户是否异常
            $check = $this->checkParamAbnormal($abnormal, $toUserIds);
            if($check['code'] != Hint::SUCCESS) {
                $result = $check;
                break;
            }
            //获取礼物数据
            $check = $this->getGiftInfo($placeType, $giftId, $giftData);
            if($check['code'] != Hint::SUCCESS) {
                $result = $check;
                break;
            }
            //校验背包数量
            $check = $this->checkBagNum($fromUserId, $toUserIds, $giftId, $giftNum);
            if($check['code'] != Hint::SUCCESS) {
                $result = $check;
                break;
            }
            //不能从背包赠送的
            if(in_array($giftData['gift_type'],[5,8,9]) && $placeType==2){
                $result = [
                    'code' => Hint::ERR_NORMAL,
                    'message' => '该礼物不支持背包赠送',
                    'data' => [],
                ];
                break;
            }
            //扣背包礼物记录礼物流水
            $streamList = [];//礼物流水
            DB::beginTransaction();
            try {
                foreach($toUserIds as $toUserId) {
                    //扣背包礼物
                    $this->giftBagModel->inc($fromUserId, $toUserId, $giftId, -$giftNum);

                    //礼物价格
                    $giftPrice = $giftData['price'];
                    //普通礼物 富豪值礼物
                    if(in_array($giftData['gift_type'], [1, 4, 10, 11, 13])) {
                        //礼物流水
                        $streamLog = [
                            'user_id' => $toUserId,
                            'from_user_id' => $fromUserId,
                            'gift_id' => $giftId,
                            'gift_name' => $giftData['name'],
                            'gift_price' => $giftPrice,
                            'gift_image' => $giftData['image'],
                            'gift_type' => $giftData['gift_type'],
                            'gift_num' => $giftNum,
                            'change_timestamp' => $now,
                            'room_id' => $roomId,
                            'type' => $placeType
                        ];
                        $streamId = $this->giftModel->addStream($streamLog);
                        $streamLog['stream_id'] = $streamId;
                        $streamLog['base_gift_price'] = $giftPrice;
                        $streamLog['wealth_num'] = $giftData['wealth_num'];//自定义富豪值
                        $streamLog['hot_num'] = $giftData['hot_num'];//自定义热度值
                        $streamList[] = $streamLog;
                    }
                    //幸运礼物 新幸运礼物
                    if(in_array($giftData['gift_type'], [2, 7])) {
                        //礼物流水
                        $streamLog = [
                            'user_id' => $toUserId,
                            'from_user_id' => $fromUserId,
                            'gift_id' => $giftId,
                            'gift_name' => $giftData['name'],
                            'gift_price' => intval($giftPrice/10),
                            'gift_image' => $giftData['image'],
                            'gift_type' => $giftData['gift_type'],
                            'gift_num' => $giftNum,
                            'change_timestamp' => $now,
                            'room_id' => $roomId,
                            'type' => $placeType
                        ];
                        $streamId = $this->giftModel->addStream($streamLog);
                        $streamLog['stream_id'] = $streamId;
                        $streamLog['base_gift_price'] = $giftPrice;
                        $streamLog['wealth_num'] = $giftData['wealth_num'];//自定义富豪值
                        $streamList[] = $streamLog;
                    }
                    //盲盒礼物
                    if($giftData['gift_type'] == 3) {
                        $streamLogBase = [
                            'user_id' => $toUserId,
                            'from_user_id' => $fromUserId,
                            'gift_id' => $giftId,
                            'gift_name' => $giftData['name'],
                            'gift_price' => 0,
                            'gift_image' => $giftData['image'],
                            'gift_type' => $giftData['gift_type'],
                            'gift_num' => 0,
                            'change_timestamp' => $now,
                            'room_id' => $roomId,
                            'type' => $placeType
                        ];
                        //根据概率计算
                        $logList = [];
                        for($i=1;$i<=$giftNum;$i++) {
                            $multipleNum = probabilityAlgorithm($giftData['ext_data']);
                            if(!isset($logList[$multipleNum])) {
                                $logList[$multipleNum] = $streamLogBase;
                                $logList[$multipleNum]['gift_price'] = $multipleNum;
                            }
                            $logList[$multipleNum]['gift_num'] = $logList[$multipleNum]['gift_num'] + 1;
                        }
                        //礼物流水
                        foreach($logList as $streamLog) {
                            $streamId = $this->giftModel->addStream($streamLog);
                            $streamLog['stream_id'] = $streamId;
                            $streamLog['base_gift_price'] = $giftPrice;
                            $streamList[] = $streamLog;
                        }
                    }
                    //套盒礼物
                    if($giftData['gift_type'] == 6) {
                        //礼物流水
                        $streamLog = [
                            'user_id' => $toUserId,
                            'from_user_id' => $fromUserId,
                            'gift_id' => $giftId,
                            'gift_name' => $giftData['name'],
                            'gift_price' => $giftPrice,
                            'gift_image' => $giftData['image'],
                            'gift_type' => $giftData['gift_type'],
                            'gift_num' => $giftNum,
                            'change_timestamp' => $now,
                            'room_id' => $roomId,
                            'type' => $placeType
                        ];
                        $streamId = $this->giftModel->addStream($streamLog);
                        $streamLog['stream_id'] = $streamId;
                        $streamLog['base_gift_price'] = $giftPrice;
                        $streamLog['wealth_num'] = $giftData['wealth_num'];//自定义富豪值
                        $streamList[] = $streamLog;
                        //套盒内包含的礼物
                        foreach($giftData['ext_data'] as $extGift) {
                            $streamLog = [
                                'user_id' => $toUserId,
                                'from_user_id' => $fromUserId,
                                'gift_id' => $extGift['gift_id'],
                                'gift_name' => $extGift['name'],
                                'gift_price' => 0,
                                'gift_image' => $extGift['image'],
                                'gift_type' => $extGift['gift_type'],
                                'gift_num' => $giftNum,
                                'change_timestamp' => $now,
                                'room_id' => $roomId,
                                'type' => $placeType
                            ];
                            $streamLog['stream_id'] = $streamId;
                            $streamLog['base_gift_price'] = 0;
                            $streamLog['wealth_num'] = 0;//自定义富豪值
                            $streamLog['hide_msg'] = 1;//是否隐藏页面信息
                            $streamList[] = $streamLog;
                        }
                    }
                    //热度卡处理
                    if($giftData['gift_type'] == 10){
                        //获取房间记录id
                        $roomOpenId = $this->roomModel->getRoomOpenList($roomId, 'roomOpenId');
                        if(empty($roomOpenId)) {
                            continue;
                        }
                        //获取房间开启记录
                        $openLog = $this->roomModel->getRoomOpenLog($roomOpenId);

                        //记录热度卡送出记录
                        $finalHotNum = $giftNum * $giftData['hot_num'];
                        $insert = [
                            'room_id' => $roomId,
                            'gift_id' => $giftId,
                            'user_id' =>  $toUserId,
                            'from_user_id' => $fromUserId,
                            'hot_num' => $finalHotNum,
                            'gift_num' => $giftNum,
                            'gift_stream_id' => $streamId,
                            'open_room_log_id' => $openLog['id'],
                            'created_at' => date('Y-m-d H:i:s',$now)
                        ];
                        $this->giftModel->insertHotGiftCard($insert);
                    }
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                $result['code'] = Hint::ERROR;
                write_log('error_notice', 'sendGiftByBag 背包送礼失败 数据已回滚', ['msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
                break;
            }

            //返回值
            $result['code'] = Hint::SUCCESS;
            $result['data'] = $streamList;
            //金币
            $this->handleKkBalance($streamList, $roomId, $roomInfo);

            //发送消息
            //$this->handleSendMsg($placeType, $roomId, $fromUserId, $streamList, $giftData, $giftNum);

            //MQ
            $this->handleMq(1, $streamList);

            //房间流水
            $this->handleRoomWealthBalance($streamList, $is_certified);
            //财富值
            $this->handleWealthBalance($streamList);
            //魅力值
	    $this->handleCharmBalance($streamList);

	    //发送消息
	    $this->handleSendMsg($placeType, $roomId, $fromUserId, $streamList, $giftData, $giftNum);

            //主播收礼排行榜
            $this->handleAnchorAcceptGiftRank($streamList);

            //房间团战
            $this->handleGame($streamList);
            //跨房PK
            $this->handCrossRoomPkHandleGame($streamList,$giftData);
            //幸运礼物抽奖
            if($giftData['gift_type'] == 2) {
                $this->handleLuckGift($streamList, $giftData, $giftNum, $fromUserId, $roomId);
            }
            //新幸运礼物抽奖
            if($giftData['gift_type'] == 7) {
                //送礼消耗钻石数 总计
                $diamondNumAll = $giftData['price'] * $giftNum * count($toUserIds);
                $this->handleLuckGiftV2($diamondNumAll, $giftData, ($giftNum*count($toUserIds)), $fromUserId, $roomId);
            }
            //商品礼物处理
            if($giftData['gift_type'] == 11) {
                $this->handleGiftGoods($giftData, $giftNum, $fromUserId, $toUserIds, $roomId);
            }
            //拍拍房处理
            if(!empty($roomId)) {
                $this->doRoomPaiPai($roomId, $roomInfo, $streamList);
            }
            //用户礼物数量统计
            $this->handleUserGiftStatistics($streamList);

        } while (false);

        return $result;
    }

    /**
     * 钻石购买赠送礼物 同步处理所有
     */
    public function sendGiftByDiamond($fromUserId, $toUserIds, $giftId, $giftNum, $roomId, $abnormal=0, $extData=[]) {
        $result = [
            'code' => Hint::ERROR,
            'message' => '',
            'data' => [],
        ];
	$now = time();
        do {
            $placeType = 1;//礼物来源 1=购买 2=背包
            $giftData = [];//礼物信息
            $roomInfo = [];//房间信息
            $is_certified = 0;//房间是否认证
            //房间信息
            if($roomId > 0) {
                $roomInfo = $this->roomModel->get_room($roomId);
                if(empty($roomInfo)) {
                    $result['code'] = Hint::PARAM_ERROR;
                    $result['message'] = '房间不存在';
                    break;  
                }
                $is_certified = $roomInfo['certified'];
            }
            //校验基本参数
            $check = $this->checkParam($fromUserId, $toUserIds, $giftId, $giftNum, $roomId);
            if($check['code'] != Hint::SUCCESS) {
                $result = $check;
                break;
            }
            //校验收礼用户账户是否异常
            $check = $this->checkParamAbnormal($abnormal, $toUserIds);
            if($check['code'] != Hint::SUCCESS) {
                $result = $check;
                break;
            }
            //判断用户是否在禁止消费名单
            $check = $this->userFilterService->inConsumeUserBlacklist($fromUserId);
            if($check){
                $result['code'] = Hint::ROOM_GIFT_USER_CONSUME_FORBID;
                break;
            }
            //添加消费限制
            $check = $this->financeService->reachConsumeToplimit($fromUserId);
            if($check){
                $result['code'] = Hint::FINANCE_CONSUME_TOPLIMIT;
                break;
            }
            //获取礼物数据
            $check = $this->getGiftInfo($placeType, $giftId, $giftData);
            if($check['code'] != Hint::SUCCESS) {
                $result = $check;
                break;
            }
            //礼物类型
            if(!in_array($giftData['gift_type'], [1, 2, 3, 4, 6, 7, 8, 11])) {
                $result['code'] = Hint::PARAM_ERROR;
                break;
            }
            //若是增值服务的话礼物价格处理
            if($giftData['gift_type'] == 8){
                $giftData['price'] = $extData['costDiamond'];//实际扣除金额
            }
            //校验财富等级
            $check = $this->checkWealth($fromUserId, $giftData);
            if($check['code'] != Hint::SUCCESS) {
                $result = $check;
                break;
            }
            //送礼消耗钻石数 每人
            $diamondNumOne = $giftData['price'] * $giftNum;
            //送礼消耗钻石数 总计
            $diamondNumAll = $giftData['price'] * $giftNum * count($toUserIds);
            //校验账户余额
            $check = $this->checkUserDiamondWallet($fromUserId, $diamondNumAll);
            if($check['code'] != Hint::SUCCESS) {
                $result = $check;
                break;
            }

            //礼物流水
            $streamList = [];
            $diamond_desc = ($roomId > 0) ? $this->descConf['room_gift_consume_diamond'] : $this->descConf['gift_consume_diamond'];
            DB::beginTransaction();
            try {
                foreach($toUserIds as $toUserId) {
                    //扣钻石
                    if($diamondNumOne != 0) {
                        $this->diamondModel->inc($fromUserId, $toUserId, $roomId, 0, 0 - $diamondNumOne, $diamond_desc);
                    }

                    //礼物价格
                    $giftPrice = $giftData['price'];
                    //普通礼物 富豪值礼物 商品礼物
                    if(in_array($giftData['gift_type'], [1, 4, 11, 13])) {
                        //礼物流水
                        $streamLog = [
                            'user_id' => $toUserId,
                            'from_user_id' => $fromUserId,
                            'gift_id' => $giftId,
                            'gift_name' => $giftData['name'],
                            'gift_price' => $giftPrice,
                            'gift_image' => $giftData['image'],
                            'gift_type' => $giftData['gift_type'],
                            'gift_num' => $giftNum,
                            'change_timestamp' => $now,
                            'room_id' => $roomId,
                            'type' => $placeType
                        ];
                        $streamId = $this->giftModel->addStream($streamLog);
                        $streamLog['stream_id'] = $streamId;
                        $streamLog['base_gift_price'] = $giftPrice;
                        $streamLog['wealth_num'] = $giftData['wealth_num'];//自定义富豪值
                        $streamList[] = $streamLog;
                    }
                    //幸运礼物 新幸运礼物
                    if(in_array($giftData['gift_type'], [2, 7])) {
                        //礼物流水
                        $streamLog = [
                            'user_id' => $toUserId,
                            'from_user_id' => $fromUserId,
                            'gift_id' => $giftId,
                            'gift_name' => $giftData['name'],
                            'gift_price' => intval($giftPrice/10),
                            'gift_image' => $giftData['image'],
                            'gift_type' => $giftData['gift_type'],
                            'gift_num' => $giftNum,
                            'change_timestamp' => $now,
                            'room_id' => $roomId,
                            'type' => $placeType
                        ];
                        $streamId = $this->giftModel->addStream($streamLog);
                        $streamLog['stream_id'] = $streamId;
                        $streamLog['base_gift_price'] = $giftPrice;
                        $streamLog['wealth_num'] = 0;
                        $streamList[] = $streamLog;
                    }
                    //盲盒礼物
                    if($giftData['gift_type'] == 3) {
                        $streamLogBase = [
                            'user_id' => $toUserId,
                            'from_user_id' => $fromUserId,
                            'gift_id' => $giftId,
                            'gift_name' => $giftData['name'],
                            'gift_price' => 0,
                            'gift_image' => $giftData['image'],
                            'gift_type' => $giftData['gift_type'],
                            'gift_num' => 0,
                            'change_timestamp' => $now,
                            'room_id' => $roomId,
                            'type' => $placeType
                        ];
                        //根据概率计算
                        $logList = [];
                        for($i=1;$i<=$giftNum;$i++) {
                            $multipleNum = probabilityAlgorithm($giftData['ext_data']);
                            if(!isset($logList[$multipleNum])) {
                                $logList[$multipleNum] = $streamLogBase;
                                $logList[$multipleNum]['gift_price'] = $multipleNum;
                            }
                            $logList[$multipleNum]['gift_num'] = $logList[$multipleNum]['gift_num'] + 1;
                        }
                        //礼物流水
                        foreach($logList as $streamLog) {
                            $streamId = $this->giftModel->addStream($streamLog);
                            $streamLog['stream_id'] = $streamId;
                            $streamLog['base_gift_price'] = $giftPrice;
                            $streamList[] = $streamLog;
                        }
                    }
                    //套盒礼物
                    if($giftData['gift_type'] == 6) {
                        //礼物流水
                        $streamLog = [
                            'user_id' => $toUserId,
                            'from_user_id' => $fromUserId,
                            'gift_id' => $giftId,
                            'gift_name' => $giftData['name'],
                            'gift_price' => $giftPrice,
                            'gift_image' => $giftData['image'],
                            'gift_type' => $giftData['gift_type'],
                            'gift_num' => $giftNum,
                            'change_timestamp' => $now,
                            'room_id' => $roomId,
                            'type' => $placeType
                        ];
                        $streamId = $this->giftModel->addStream($streamLog);
                        $streamLog['stream_id'] = $streamId;
                        $streamLog['base_gift_price'] = $giftPrice;
                        $streamLog['wealth_num'] = $giftData['wealth_num'];//自定义富豪值
                        $streamList[] = $streamLog;
                        //套盒内包含的礼物
                        foreach($giftData['ext_data'] as $extGift) {
                            $streamLog = [
                                'user_id' => $toUserId,
                                'from_user_id' => $fromUserId,
                                'gift_id' => $extGift['gift_id'],
                                'gift_name' => $extGift['name'],
                                'gift_price' => 0,
                                'gift_image' => $extGift['image'],
                                'gift_type' => $extGift['gift_type'],
                                'gift_num' => $giftNum,
                                'change_timestamp' => $now,
                                'room_id' => $roomId,
                                'type' => $placeType
                            ];
                            $streamLog['stream_id'] = 0;
                            $streamLog['base_gift_price'] = 0;
                            $streamLog['wealth_num'] = 0;//自定义富豪值
                            $streamLog['hide_msg'] = 1;//是否隐藏页面信息
                            $streamList[] = $streamLog;
                        }
                    }
                    //增值服务-守护麦服务
                    if($giftData['gift_type'] == 8) {
                        //礼物流水
                        $streamLog = [
                            'user_id' => $toUserId,
                            'from_user_id' => $fromUserId,
                            'gift_id' => $giftId,
                            'gift_name' => $giftData['name'],
                            'gift_price' => $giftPrice,
                            'gift_image' => $giftData['image'],
                            'gift_type' => $giftData['gift_type'],
                            'gift_num' => $giftNum,
                            'change_timestamp' => $now,
                            'room_id' => $roomId,
                            'type' => $placeType
                        ];
                        $streamId = $this->giftModel->addStream($streamLog);
                        $streamLog['stream_id'] = $streamId;
                        $streamLog['base_gift_price'] = $giftPrice;
                        $streamLog['wealth_num'] = 0;
                        $streamList[] = $streamLog;
                    }
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                $result['code'] = Hint::ERROR;
                write_log('error_notice', 'sendGiftByDiamond 背包送礼失败 数据已回滚', ['msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
                break;
            }

            //返回值
            $result['code'] = Hint::SUCCESS;
            $result['data'] = $streamList;

            //金币
            $this->handleKkBalance($streamList, $roomId, $roomInfo);

            //发送消息
            //$this->handleSendMsg($placeType, $roomId, $fromUserId, $streamList, $giftData, $giftNum);

            //MQ
            $this->handleMq(1, $streamList);

            //房间流水
            $this->handleRoomWealthBalance($streamList, $is_certified);
            //财富值
            $this->handleWealthBalance($streamList);
            //魅力值
	    $this->handleCharmBalance($streamList);

	                //发送消息
	    $this->handleSendMsg($placeType, $roomId, $fromUserId, $streamList, $giftData, $giftNum);

            //主播收礼排行榜
            $this->handleAnchorAcceptGiftRank($streamList);

            //房间团战
            $this->handleGame($streamList);
            //跨房PK
            $this->handCrossRoomPkHandleGame($streamList,$giftData);
            //幸运礼物抽奖
            if($giftData['gift_type'] == 2) {
                $this->handleLuckGift($streamList, $giftData, $giftNum, $fromUserId, $roomId);
            }
            //新幸运礼物抽奖
            if($giftData['gift_type'] == 7) {
                $this->handleLuckGiftV2($diamondNumAll, $giftData, ($giftNum*count($toUserIds)), $fromUserId, $roomId);
            }
            //守护麦服务
            if($giftData['gift_type'] == 8){
                //处理增值服务
                $this->roomProtectServices->doPayHandel($giftId,$fromUserId,$toUserId,$roomId, $extData);
            }
            //商品礼物处理
            if($giftData['gift_type'] == 11) {
                $this->handleGiftGoods($giftData, $giftNum, $fromUserId, $toUserIds, $roomId);
            }
            //拍拍房处理
            if(!empty($roomId)) {
                $this->doRoomPaiPai($roomId, $roomInfo, $streamList);
            }
            //用户礼物数量统计
            $this->handleUserGiftStatistics($streamList);

	    //飘屏
            $this->handleSendFull($fromUserId, $toUserIds, $giftData, $giftNum);

        } while (false);

        return $result;
    }

    /**
     * 新幸运礼物
     */
    public function newLuckGiftCombo($fromUserId, $toUserIds, $giftId, $giftNum, $roomId, $giftData) {
        $result = [
            'code' => Hint::SUCCESS,
            'message' => '',
            'data' => [],
        ];

        if ($giftNum > 1) {
            $result['code'] = Hint::ROOM_ROCKON_GIFT_SEND_NUM_ERROR;
            $result['message'] = '幸运礼物单次仅限赠送1个哦';
            return $result;
        }

//        if (count($toUserIds) > 1) {
//            $result['code'] = Hint::ROOM_ROCKON_GIFT_SEND_NUM_ERROR;
//            $result['message'] = '幸运礼物仅限赠送1人哦';
//            return $result;
//        }


        $now = time();
        $lock_key = 'newluckgiftcombo' . $fromUserId;
        if (!redis_lock($lock_key, 5)){
            $result['code'] = Hint::NOT_FREQ;
            return $result;
        }

        do {
            $placeType = 1;//礼物来源 1=购买 2=背包


            //获取礼物数据
//            $giftData = [];//礼物信息
//            $check = $this->getGiftInfo($placeType, $giftId, $giftData);
//            if($check['code'] != Hint::SUCCESS) {
//                $result = $check;
//                break;
//            }

            //礼物类型
            if($giftData['gift_type'] != 7) {
                $result['code'] = Hint::PARAM_ERROR;
                break;
            }

            //礼物价格
            $giftPrice = $giftData['price'];

            //送礼消耗钻石数 每人
            $diamondNumOne = $giftData['price'] * $giftNum;

            //送礼消耗钻石数 总计
            $diamondNumAll = $giftData['price'] * $giftNum * count($toUserIds);
            //校验账户余额
            $check = $this->checkUserDiamondWallet($fromUserId, $diamondNumAll);
            if($check['code'] != Hint::SUCCESS) {
                $result = $check;
                break;
            }

            // 扣钻石
            //礼物流水
            $streamList = [];
            $streamLog = [];
            $luckGiftStreamLog = [];
            $diamond_desc = ($roomId > 0) ? $this->descConf['room_gift_consume_diamond'] : $this->descConf['gift_consume_diamond'];
            DB::beginTransaction();
            try {
                foreach($toUserIds as $toUserId) {
                    //扣钻石
                    if($diamondNumOne != 0) {
                        $this->diamondModel->inc($fromUserId, $toUserId, $roomId, 0, 0 - $diamondNumOne, $diamond_desc);
                    }

                    $streamLog = [
                        'user_id' => $toUserId,
                        'from_user_id' => $fromUserId,
                        'gift_id' => $giftId,
                        'gift_name' => $giftData['name'],
                        'gift_price' => intval(bcmul($giftPrice, 0.01)),//1:100
                        'gift_image' => $giftData['image'],
                        'gift_type' => $giftData['gift_type'],
                        'gift_num' => $giftNum,
                        'change_timestamp' => $now,
                        'room_id' => $roomId,
                        'type' => $placeType
                    ];
//                    $streamId = $this->giftModel->addStream($streamLog);

                    $luckGiftStreamLog[] = $streamLog;

//                    $streamLog['stream_id'] = $streamId;
//                    $streamLog['base_gift_price'] = $giftPrice;
//                    $streamLog['wealth_num'] = 0;
                    $streamList[] = $streamLog;

                }

                $this->giftModel->addBatchLuckGiftStream($streamList);

                //返回值
                $result['code'] = Hint::SUCCESS;

                $pub_res['code'] = Hint::SUCCESS;

                $requestData = [
                    'queue_route' => 'global.newluckgiftim',
                    'data' => [
                        'from_user_id' => $fromUserId,
                        'to_user_ids' => $toUserIds,
                        'gift_id' => $giftId,
                        'gift_data' => $giftData,
                        'gift_num' => $giftNum,
                        'room_id' => $roomId,
                        'stream_list' => $streamList,
                        'diamond_num_all' => $diamondNumAll,
                    ],
                ];

                $publishObject = Publisher::getInstance();
                $publishObject->requestData = $requestData;
                $pub_res = $publishObject->publisher();
//                $this->newluckgiftimHandle($requestData['data']);

//                $requestData = [
//                    'queue_route' => 'global.newluckgift',
//                    'data' => [
//                        'from_user_id' => $fromUserId,
//                        'to_user_ids' => $toUserIds,
//                        'gift_id' => $giftId,
//                        'gift_data' => $giftData,
//                        'gift_num' => $giftNum,
//                        'room_id' => $roomId,
//                        'stream_list' => $streamList,
//                    ],
//                ];
//
//                $publishObject = Publisher::getInstance();
//                $publishObject->requestData = $requestData;
//                $pub_res = $publishObject->publisher();
//                if ($pub_res['code'] != Hint::SUCCESS) {
////                    throw new \Exception($pub_res['msg'] ?? '消息发送失败');
//                    write_log('error_newLuckGiftCombo', 'newluckgift publisher 失败', ['msg'=>$pub_res['msg'] ?? '消息发送失败']);
//		        }

//		        $this->newluckgiftHandle($requestData['data']);

                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                $result['code'] = Hint::ERROR;
                write_log('error_newLuckGiftCombo', 'newLuckGiftCombo 新幸运礼物送礼失败 数据已回滚', ['msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
                break;
            }

        } while (false);

        redis_unlock($lock_key);

        return $result;
    }

    public function newluckgiftimHandle($body) {
        $result = [
            'code' => Hint::SUCCESS,
            'message' => '',
            'data' => [],
        ];

        do {
            if(empty($body['from_user_id']) || empty($body['to_user_ids']) || empty($body['gift_id']) || empty($body['gift_num'])  || empty($body['stream_list'])) {
                $result['message'] = 'param error';
                break;
            }

            $fromUserId = $body['from_user_id'];
            $toUserIds = $body['to_user_ids'];
//            $toUserList = $this->model_user->get_users_by_ids($toUserIds);
//            $toUserNameList = array_column($toUserList, 'nickname');
//            $toUserName = implode('、', $toUserNameList);

            $giftId = $body['gift_id'];
            $giftData = $body['gift_data'];
            $giftNum = $body['gift_num'];
            $streamList = $body['stream_list'];
            $diamondNumAll = $body['diamond_num_all'];
            $roomId = $body['room_id'] ?: 0;

            $this->handleLuckGiftV2($diamondNumAll, $giftData, ($giftNum*count($toUserIds)), $fromUserId, $roomId, $toUserIds);

            $this->_sendNewLuckGiftBroadcastGift($streamList, $roomId, $fromUserId, $toUserIds, $giftData, $giftNum);

        } while (false);

        if ($result['code'] != Hint::SUCCESS) {
            write_log('error_notice', 'newluckgiftimHandle consumer fail', ['code'=>$result['code'], 'msg'=>$result['message']]);
        }
    }

    public function newluckgiftHandle($body) {
        $result = [
            'code' => Hint::SUCCESS,
            'message' => '',
            'data' => [],
        ];

        do {
            if(empty($body['from_user_id']) || empty($body['to_user_ids']) || empty($body['gift_id']) || empty($body['gift_num'])  || empty($body['stream_list'])) {
                $result['message'] = 'param error';
                break;
            }

            $fromUserId = $body['from_user_id'];
            $toUserIds = $body['to_user_ids'];
            $giftId = $body['gift_id'];
            $giftData = $body['gift_data'];
            $giftNum = $body['gift_num'];
            $streamList = $body['stream_list'];
            $roomId = $body['room_id'] ?: 0;

            $placeType = 1;//礼物来源 1=购买 2=背包
            $roomInfo = [];//房间信息
            $is_certified = 0;//房间是否认证
            $now = time();
            //房间信息
            if($roomId > 0) {
                $roomInfo = $this->roomModel->get_room($roomId);
                if(empty($roomInfo)) {
                    $result['code'] = Hint::PARAM_ERROR;
                    $result['message'] = '房间不存在';
                    break;
                }
                $is_certified = $roomInfo['certified'];
            }

            //礼物类型
            if($giftData['gift_type'] != 7) {
                $result['code'] = Hint::PARAM_ERROR;
                break;
            }

            //礼物价格
            $giftPrice = $giftData['price'];

            //送礼消耗钻石数 总计
            $diamondNumAll = $giftData['price'] * $giftNum * count($toUserIds);

            //礼物流水
//            $streamList = [];
//            foreach($toUserIds as $toUserId) {
//                $streamLog = [
//                    'user_id' => $toUserId,
//                    'from_user_id' => $fromUserId,
//                    'gift_id' => $giftId,
//                    'gift_name' => $giftData['name'],
//                    'gift_price' => intval($giftPrice/10),
//                    'gift_image' => $giftData['image'],
//                    'gift_type' => $giftData['gift_type'],
//                    'gift_num' => $giftNum,
//                    'change_timestamp' => $now,
//                    'room_id' => $roomId,
//                    'type' => $placeType
//                ];
//                $streamId = $this->giftModel->addStream($streamLog);
//                $streamLog['stream_id'] = $streamId;
//                $streamLog['base_gift_price'] = $giftPrice;
//                $streamLog['wealth_num'] = 0;
//                $streamList[] = $streamLog;
//            }

            //返回值
            $result['code'] = Hint::SUCCESS;

            $this->handleNewLuckGiftSendMsg($placeType, $roomId, $fromUserId, $streamList, $giftData, $giftNum);

            //金币
            $this->handleKkBalance($streamList, $roomId, $roomInfo);

            //MQ
            $this->handleMq(1, $streamList);

            //房间流水
            $this->handleRoomWealthBalance($streamList, $is_certified);
            //财富值
            $this->handleWealthBalance($streamList);
            //魅力值
            $this->handleCharmBalance($streamList);

            //发送消息
            //$this->handleSendMsg($placeType, $roomId, $fromUserId, $streamList, $giftData, $giftNum);

            //主播收礼排行榜
            $this->handleAnchorAcceptGiftRank($streamList);

            //房间团战
//            $this->handleGame($streamList);

            //跨房PK
//	    $this->handCrossRoomPkHandleGame($streamList,$giftData);

	    //$this->handleLuckGiftV2($diamondNumAll, $giftData, ($giftNum*count($toUserIds)), $fromUserId, $roomId);

            //拍拍房处理
//            if(!empty($roomId)) {
//                $this->doRoomPaiPai($roomId, $roomInfo, $streamList);
//            }
            //用户礼物数量统计
            $this->handleUserGiftStatistics($streamList);

            //飘屏
//            $this->handleSendFull($fromUserId, $toUserIds, $giftData, $giftNum);

//            $time = mt_rand(1, 5);
//            sleep(1);

        } while (false);

        if ($result['code'] != Hint::SUCCESS) {
            write_log('error_sendGift', 'newluckgiftHandle consumer fail', ['code'=>$result['code'], 'msg'=>$result['message']]);
        }
    }

    /**
     * 钻石购买赠送礼物 异步处理消息 彩蛋礼物
     */
    public function sendGiftByDiamondByColor($fromUserId, $toUserIds, $giftId, $giftNum, $roomId, $abnormal=0, $extData=[]) {
        $result = [
            'code' => Hint::ERROR,
            'message' => '',
            'data' => [],
        ];
        $now = time();
        do {
            $placeType = 1;//礼物来源 1=购买 2=背包
            $giftData = [];//礼物信息
            $is_certified = 0;//房间是否认证
            //房间信息
            if($roomId > 0) {
                $roomInfo = $this->roomModel->get_room($roomId);
                if(empty($roomInfo)) {
                    $result['code'] = Hint::PARAM_ERROR;
                    $result['message'] = '房间不存在';
                    break;  
                }
                 $is_certified = $roomInfo['certified'];
            }
            //校验基本参数
            $check = $this->checkParam($fromUserId, $toUserIds, $giftId, $giftNum, $roomId);
            if($check['code'] != Hint::SUCCESS) {
                $result = $check;
                break;
            }
            //校验收礼用户账户是否异常
            $check = $this->checkParamAbnormal($abnormal, $toUserIds);
            if($check['code'] != Hint::SUCCESS) {
                $result = $check;
                break;
            }
            //判断用户是否在禁止消费名单
            $check = $this->userFilterService->inConsumeUserBlacklist($fromUserId);
            if($check){
                $result['code'] = Hint::ROOM_GIFT_USER_CONSUME_FORBID;
                break;
            }
            //添加消费限制
            $check = $this->financeService->reachConsumeToplimit($fromUserId);
            if($check){
                $result['code'] = Hint::FINANCE_CONSUME_TOPLIMIT;
                break;
            }
            //获取礼物数据
            $check = $this->getGiftInfo($placeType, $giftId, $giftData);
            if($check['code'] != Hint::SUCCESS) {
                $result = $check;
                break;
            }
            //礼物类型
            if(!in_array($giftData['gift_type'], [5])) {
                $result['code'] = Hint::PARAM_ERROR;
                break;
            }
            //若是增值服务的话礼物价格处理
            if($giftData['gift_type'] == 8){
                $giftData['price'] = $extData['costDiamond'];//实际扣除金额
            }
            //送礼消耗钻石数 每人
            $diamondNumOne = $giftData['price'] * $giftNum;
            //送礼消耗钻石数 总计
            $diamondNumAll = $giftData['price'] * $giftNum * count($toUserIds);
            //礼物总数量
            $giftNumAll = $giftNum * count($toUserIds);

            //礼物抵扣券
            $useDeductGiftNum = 0;//本次抽奖使用的礼物抵扣券数量
            $deductGiftId = 0;//礼物抵扣券礼物ID
            $deductGiftMap = $this->giftModel->getGiftDeductByUserId($fromUserId);
            if(!empty($deductGiftMap) && !empty($deductGiftMap[$giftId])) {
                $deductGiftId = $deductGiftMap[$giftId]['gift_id'];
                $deductGiftMap[$giftId]['use_gift_price'] = $deductGiftMap[$giftId]['price'];
                if($deductGiftMap[$giftId]['price'] >= $giftData['price']) {
                    $deductGiftMap[$giftId]['use_gift_price'] = $giftData['price'];
                }

                $deductGiftNum = (int) $deductGiftMap[$giftId]['gift_num'];
                if($deductGiftNum > 0) {
                    if($deductGiftNum >= $giftNumAll) {
                        $useDeductGiftNum = $giftNumAll;
                    }else{
                        $useDeductGiftNum = $deductGiftNum;
                    }

                    //使用礼物抵扣券 那么消耗钻石变少
                    $diamondNumAll = $diamondNumAll - $deductGiftMap[$giftId]['use_gift_price']*$useDeductGiftNum;
                }
            }

            //校验账户余额
            $check = $this->checkUserDiamondWallet($fromUserId, $diamondNumAll);
            if($check['code'] != Hint::SUCCESS) {
                $result = $check;
                break;
            }

            DB::beginTransaction();
            try{
                //扣钻石
                $diamond_desc = ($roomId > 0) ? $this->descConf['room_gift_consume_diamond'] : $this->descConf['gift_consume_diamond'];
                if($diamondNumAll > 0) {
                    $this->diamondModel->inc($fromUserId, 0, $roomId, 0, (0 - $diamondNumAll), $diamond_desc);
                }

                //扣礼物抵扣券
                if($useDeductGiftNum > 0) {
                    $this->giftBagModel->inc($fromUserId, 0, $deductGiftId, -$useDeductGiftNum, 12, $now);
                }

                DB::commit();
            }catch(\Exception $e){
                DB::rollBack();
                $result['code'] = Hint::DIAMOND_NOT_ENOUGH;
                break;
            }

            //彩蛋抽奖
            $colorGiftLogList = [];
            if($giftData['gift_type'] == 5){
                //新彩蛋爆出逻辑
                $colorRes = $this->colorGiftServices->colorGiftDraw($giftId, $giftNum, $fromUserId, $roomId, $toUserIds, $now, $giftData);
                if(empty($colorRes['data'])){
                    $result['code'] = Hint::ERROR;
                    $result['msg'] = '系统异常,处理结果失败 code:703';
                    break;
                }
                $colorGiftLogList = $colorRes['data'];
            }

            //礼物流水
            $streamList = [];

            DB::beginTransaction();
            try {
                foreach($toUserIds as $toUserId) {
                    //礼物价格
                    $giftPrice = $giftData['price'];

                    //彩蛋礼物流水
                    if($giftData['gift_type'] == 5){
                        //彩蛋礼物流水
                        $streamLog = [
                            'user_id' => $toUserId,
                            'from_user_id' => $fromUserId,
                            'gift_id' => $giftId,
                            'gift_name' => $giftData['name'],
                            'gift_price' => 0,
                            'gift_image' => $giftData['image'],
                            'gift_type' => $giftData['gift_type'],
                            'gift_num' => $giftNum,
                            'change_timestamp' => $now,
                            'room_id' => $roomId,
                            'type' => $placeType
                        ];
                        $streamLog['base_gift_price'] = $giftPrice;
                        $streamLog['wealth_num'] = 0;
                        $streamList[] = $streamLog;
                        //爆出流水
                        foreach($colorGiftLogList[$toUserId] as $v){
                            $streamLog = [
                                'user_id' => $toUserId,
                                'from_user_id' => $fromUserId,
                                'gift_id' => $v['gift_id'],
                                'gift_name' => empty($v['giftInfo']['name']) ? '' : $v['giftInfo']['name'],
                                'gift_price' => empty($v['giftInfo']['price']) ? 0 : $v['giftInfo']['price'],
                                'gift_image' => empty($v['giftInfo']['image']) ? '' : $v['giftInfo']['image'],
                                'gift_type' => empty($v['giftInfo']['gift_type']) ? 0 : $v['giftInfo']['gift_type'],
                                'gift_num' => 1,
                                'change_timestamp' => $now,
                                'room_id' => $roomId,
                                'type' => 1,
                                'pop_stream' => 1,
                                'color_gift_id' => $giftId,
                                'pool_id' => $v['pool_id'],
                                'pool_rate_num' => $v['pool_rate_num'],
                                'from_gift_id' => $giftId,
                                'from_gift_type' => $giftData['gift_type'],
                            ];
                            if($streamLog['gift_type'] == 9) {
                                //加礼物抵扣券
                                $this->giftBagModel->inc($fromUserId, 0, $streamLog['gift_id'], $streamLog['gift_num'], 13, $now);

                                $streamId = 0;
                            }else{
                                $streamId = $this->giftModel->addStream($streamLog);
                            }
                            $streamLog['stream_id'] = $streamId;
                            $streamLog['base_gift_price'] = empty($v['giftInfo']['price']) ? 0 : $v['giftInfo']['price'];
                            $streamLog['wealth_num'] = 0;
                            $streamList[] = $streamLog;
                        }
                    }
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                $result['code'] = Hint::ERROR;
                write_log('error_notice', 'sendGiftByDiamond 背包送礼失败 数据已回滚', ['msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
                break;
            }

            //返回值
            $result['code'] = Hint::SUCCESS;
            $result['data'] = $streamList;

            //金币
            $this->handleKkBalance($streamList, $roomId, $roomInfo);
            //发送消息
            $this->handleSendMsg($placeType, $roomId, $fromUserId, $streamList, $giftData, $giftNum, $roomInfo);

            //房间流水
            $this->handleRoomWealthBalance($streamList, $is_certified);
            //财富值
            $this->handleWealthBalance($streamList);
            //魅力值
            $this->handleCharmBalance($streamList);

            //拍拍房处理
            if(!empty($roomId)) {
                $this->doRoomPaiPai($roomId, $roomInfo, $streamList);
            }

            //MQ 送礼物异步处理
            $this->handleMqForAsyn($placeType, $fromUserId, $toUserIds, $giftNum, $is_certified, $giftData, $roomId, $streamList, $now);
            //MQ 普通送礼
            $this->handleMq(1, $streamList);
        } while (false);

        return $result;
    }

    /**
     * 送礼物异步处理-财富值魅力值
     */
    public function sendGiftAsynForWealthCharm($body){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        //从redis中取出key
        $body = Redis::get($this->colorGiftMqKey.$body['mqredis']);
        $body = json_decode($body,true);
        do{
            if(empty($body['placeType']) || empty($body['fromUserId']) || empty($body['toUserIds'])|| empty($body['giftNum'])|| empty($body['giftData'])|| empty($body['streamList'])|| empty($body['now'])) {
                write_log('error_sendGift', 'sendGiftAsynForWealthCharm 接受参数异常', $body);
                break;
            }

            $placeType = $body['placeType'];
            $fromUserId = $body['fromUserId'];
            $toUserIds = $body['toUserIds'];
            $giftNum = $body['giftNum'];
            $is_certified = $body['is_certified'];
            $giftData = $body['giftData'];
            $roomId = $body['roomId'];
            $streamList = $body['streamList'];
            $now = $body['now'];

            //房间流水
            $this->handleRoomWealthBalance($streamList, $is_certified);
            //财富值
            $this->handleWealthBalance($streamList);
            //魅力值
            $this->handleCharmBalance($streamList);

            //主播收礼排行榜
            $this->handleAnchorAcceptGiftRank($streamList);

            //用户礼物数量统计
            $this->handleUserGiftStatistics($streamList);

            //飘屏
            $this->handleSendFull($fromUserId, $toUserIds, $giftData, $giftNum);

        }while(false);

        return compact('code','msg','data');
    }

    /**
     * 送礼物异步处理-复杂礼物处理
     */
    public function sendGiftAsynForComplex($body){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        //从redis中取出key
        $body = Redis::get($this->colorGiftMqKey.$body['mqredis']);
        $body = json_decode($body,true);
        do{
            if(empty($body['placeType']) || empty($body['fromUserId']) || empty($body['toUserIds'])|| empty($body['giftNum'])|| empty($body['giftData'])|| empty($body['streamList'])|| empty($body['now'])) {
                write_log('error_sendGift', 'sendGiftAsynForComplex 接受参数异常', $body);
                break;
            }

            $placeType = $body['placeType'];
            $fromUserId = $body['fromUserId'];
            $toUserIds = $body['toUserIds'];
            $giftNum = $body['giftNum'];
            $is_certified = $body['is_certified'];
            $giftData = $body['giftData'];
            $roomId = $body['roomId'];
            $streamList = $body['streamList'];
            $now = $body['now'];

            //幸运礼物抽奖
            if($giftData['gift_type'] == 2) {
                $this->handleLuckGift($streamList, $giftData, $giftNum, $fromUserId, $roomId);
            }
            //新幸运礼物抽奖
            if($giftData['gift_type'] == 7) {
                //送礼消耗钻石数 总计
                $diamondNumAll = $giftData['price'] * $giftNum * count($toUserIds);
                $this->handleLuckGiftV2($diamondNumAll, $giftData, ($giftNum*count($toUserIds)), $fromUserId, $roomId);
            }
            //商品礼物处理
            if($giftData['gift_type'] == 11) {
                $this->handleGiftGoods($giftData, $giftNum, $fromUserId, $toUserIds, $roomId);
            }
            //彩蛋
            if($giftData['gift_type'] == 5) {
                DB::beginTransaction();
                try {
                    foreach($streamList as $v){
                        if($v['gift_type'] != 5 && isset($v['color_gift_id'])){
                            $param = [
                                'user_id' => $v['from_user_id'],
                                'to_user_id'=> $v['user_id'],
                                'room_id' => $v['room_id'],
                                'color_id' => $v['color_gift_id'],
                                'color_gift_price' => $giftData['price'],
                                'pool_id' => $v['pool_id'],
                                'pool_rate_num' => $v['pool_rate_num'],
                                'gift_num' => $v['gift_num'],
                                'award_gift_id' => $v['gift_id'],
                                'award_gift_name' => $v['gift_name'],
                                'award_gift_price'=> $v['gift_price'],
                                'gift_stream_id'=> $v['stream_id'],
                                'award_gift_type' => $v['gift_type'],
                                'created_at' => date('Y-m-d H:i:s',time()),
                            ];
                            if($v['gift_type'] == 9) {
                                $param['to_user_id'] = $v['from_user_id'];
                            }
                            $id = $this->colorGiftRateModel->colorRandLog($param);
                        }
                    }
                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollBack();
                    $result['code'] = Hint::ERROR;
                    write_log('error_sendGift', 'sendGiftAsynForComplex 彩蛋异常', ['msg'=>$e->getMessage(),'params'=>$param]);
                    break;
                }
                //彩蛋加碎片
                $this->financeService->colorGiftDebrisIncr($fromUserId, $giftData['gift_id'], $giftData['price'] * $giftNum, $giftNum);
            }

        }while(false);

        return compact('code','msg','data');
    }

    /**
     * 送礼物异步处理-游戏
     */
    public function sendGiftAsynForGame($body){
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        //从redis中取出key
        $body = Redis::get($this->colorGiftMqKey.$body['mqredis']);
        $body = json_decode($body,true);
        do{
            if(empty($body['placeType']) || empty($body['fromUserId']) || empty($body['toUserIds'])|| empty($body['giftNum'])|| empty($body['giftData'])|| empty($body['streamList'])|| empty($body['now'])) {
                write_log('error_sendGift', 'sendGiftAsynForGame 接受参数异常', $body);
                break;
            }

            $placeType = $body['placeType'];
            $fromUserId = $body['fromUserId'];
            $toUserIds = $body['toUserIds'];
            $giftNum = $body['giftNum'];
            $is_certified = $body['is_certified'];
            $giftData = $body['giftData'];
            $roomId = $body['roomId'];
            $streamList = $body['streamList'];
            $now = $body['now'];

            //房间团战
            $this->handleGame($streamList);
            //跨房PK
            $this->handCrossRoomPkHandleGame($streamList,$giftData);

        }while(false);

        return compact('code','msg','data');
    }

    /**
     * 背包礼物批量赠送
     */
    public function bagGiftSendBatch($fromUserId, $toUserId, $roomId) {
        $result = [
            'code' => Hint::ERROR,
            'message' => '',
            'data' => [],
        ];
        do {
            if($fromUserId == $toUserId) {
                //$result['code'] = Hint::ERR_PARAMS_CHECK_FAIL;
                //$result['message'] = '不能将礼物送给自己';
                //break;
            }

            //背包礼物
            $giftBagList = $this->giftBagModel->getAll($fromUserId);
            if(empty($giftBagList)) {
                $result['code'] = Hint::THROWING_GIFT_BAG_NOT_ENOUGH;
                $result['message'] = '礼物数量不足';
                break;
            }

            //扣背包礼物 礼物批量赠送记录
            $rList = [];//礼物明细
            DB::beginTransaction();
            try {
                foreach($giftBagList as $val) {
                    if(in_array($val['gift_type'], [5,8,9])) {
                        continue;
                    }
                    //扣背包礼物
                    $this->giftBagModel->inc($fromUserId, $toUserId, $val['gift_id'], 0-$val['avail']);
                    $rList[] = ['gift_id'=>$val['gift_id'], 'gift_num'=>$val['avail']];
                }
                if(empty($rList)) {
                    DB::rollBack();
                    $result['code'] = Hint::ERROR;
                    $result['message'] = '暂无可送出礼物';
                    break;
                }

                $log = [
                    'from_user_id' => $fromUserId,
                    'to_user_id' => $toUserId,
                    'room_id' => $roomId,
                    'r_list' => json_encode($rList),
                    'status' => 0,
                    'error_res' => '',
                ];
                $batchId = $this->giftModel->addGiftSendBatch($log);
                $result['code'] = Hint::SUCCESS;

                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                $result['code'] = Hint::ERROR;
                break;
            }

            //MQ
            if(!empty($batchId)) {
                try {
                    $requestData = [
                        'queue_route' => 'global.giftbagbatch',
                        'data' => [
                            'batchId' => $batchId,
                        ],
                    ];

                    $publishObject = Publisher::getInstance();
                    $publishObject->requestData = $requestData;
                    $publishObject->publisher();
                } catch (\Exception $e) {
                    write_log('error_mq', 'global.gift.bag.batch', ['batchId'=>$batchId]);
                }
            }

        } while (false);

        return $result;
    }

    /**
     * 背包礼物批量赠送处理
     */
    public function giftbagbatchHandle($body) {
        $now = time();
        $placeType = 2;//礼物来源 1=购买 2=背包

        do {
            if(empty($body['batchId'])) {
                break;
            }
            $batchId = $body['batchId'];

            //锁
            $key = 'giftbagbatchHandle:'.$batchId;
	    $ifLock = redis_lock($key, 3600);
            if (!$ifLock){
                break;
            }

            $info = $this->giftModel->getGiftSendBatch($batchId);
            if(empty($info)) {
                break;
            }
            if($info['status'] != 0) {
                break;
            }
            //更新状态
            $this->giftModel->updateGiftSendBatch($batchId, ['status'=>1]);

            $sendGiftList = json_decode($info['r_list'], true);
            if(empty($sendGiftList)) {
                break;
            }
            $roomId = $info['room_id'];
            $fromUserId = $info['from_user_id'];
            $toUserId = $info['to_user_id'];
            $roomInfo = [];//房间信息
            $is_certified = 0;//房间是否认证
            //房间信息
            if($roomId > 0) {
                $roomInfo = $this->roomModel->get_room($roomId);
                if(!empty($roomInfo)) {
                    $is_certified = $roomInfo['certified'];
                }
            }

            //批量送礼
            $giftBatchMsgData = ['diamond_num'=>0, 'gift_list'=>[]];
            $flag = 0;
            $error_res = [];
            foreach($sendGiftList as $val) {
                $giftId = $val['gift_id'];
                $giftNum = $val['gift_num'];
                $toUserIds = [$toUserId];

                //获取礼物数据
                $check = $this->getGiftInfo(2, $giftId, $giftData);
                if($check['code'] != Hint::SUCCESS) {
                    $flag = 1;
                    $error_res[] = ['gift_id'=>$giftId, 'gift_num'=>$giftNum, 'error'=>'获取礼物数据失败'];
                    continue;
                }

                //扣背包礼物记录礼物流水
                $streamList = [];//礼物流水
                DB::beginTransaction();
                try {
                    //礼物价格
                    $giftPrice = $giftData['price'];
                    //普通礼物 富豪值礼物
                    if(in_array($giftData['gift_type'], [1, 4, 10, 11, 13])) {
                        //礼物流水
                        $streamLog = [
                            'user_id' => $toUserId,
                            'from_user_id' => $fromUserId,
                            'gift_id' => $giftId,
                            'gift_name' => $giftData['name'],
                            'gift_price' => $giftPrice,
                            'gift_image' => $giftData['image'],
                            'gift_type' => $giftData['gift_type'],
                            'gift_num' => $giftNum,
                            'change_timestamp' => $now,
                            'room_id' => $roomId,
                            'type' => $placeType
                        ];
                        $streamId = $this->giftModel->addStream($streamLog);
                        $streamLog['stream_id'] = $streamId;
                        $streamLog['base_gift_price'] = $giftPrice;
                        $streamLog['wealth_num'] = $giftData['wealth_num'];//自定义富豪值
                        $streamLog['hot_num'] = $giftData['hot_num'];
                        $streamList[] = $streamLog;
                    }
                    //幸运礼物 新幸运礼物
                    if(in_array($giftData['gift_type'], [2, 7])) {
                        //礼物流水
                        $streamLog = [
                            'user_id' => $toUserId,
                            'from_user_id' => $fromUserId,
                            'gift_id' => $giftId,
                            'gift_name' => $giftData['name'],
                            'gift_price' => intval($giftPrice/10),
                            'gift_image' => $giftData['image'],
                            'gift_type' => $giftData['gift_type'],
                            'gift_num' => $giftNum,
                            'change_timestamp' => $now,
                            'room_id' => $roomId,
                            'type' => $placeType
                        ];
                        $streamId = $this->giftModel->addStream($streamLog);
                        $streamLog['stream_id'] = $streamId;
                        $streamLog['base_gift_price'] = $giftPrice;
                        $streamLog['wealth_num'] = $giftData['wealth_num'];//自定义富豪值
                        $streamList[] = $streamLog;
                    }
                    //盲盒礼物
                    if($giftData['gift_type'] == 3) {
                        $streamLogBase = [
                            'user_id' => $toUserId,
                            'from_user_id' => $fromUserId,
                            'gift_id' => $giftId,
                            'gift_name' => $giftData['name'],
                            'gift_price' => 0,
                            'gift_image' => $giftData['image'],
                            'gift_type' => $giftData['gift_type'],
                            'gift_num' => 0,
                            'change_timestamp' => $now,
                            'room_id' => $roomId,
                            'type' => $placeType
                        ];
                        //根据概率计算
                        $logList = [];
                        for($i=1;$i<=$giftNum;$i++) {
                            $multipleNum = probabilityAlgorithm($giftData['ext_data']);
                            if(!isset($logList[$multipleNum])) {
                                $logList[$multipleNum] = $streamLogBase;
                                $logList[$multipleNum]['gift_price'] = $multipleNum;
                            }
                            $logList[$multipleNum]['gift_num'] = $logList[$multipleNum]['gift_num'] + 1;
                        }
                        //礼物流水
                        foreach($logList as $streamLog) {
                            $streamId = $this->giftModel->addStream($streamLog);
                            $streamLog['stream_id'] = $streamId;
                            $streamLog['base_gift_price'] = $giftPrice;
                            $streamList[] = $streamLog;
                        }
                    }
                    //套盒礼物
                    if($giftData['gift_type'] == 6) {
                        //礼物流水
                        $streamLog = [
                            'user_id' => $toUserId,
                            'from_user_id' => $fromUserId,
                            'gift_id' => $giftId,
                            'gift_name' => $giftData['name'],
                            'gift_price' => $giftPrice,
                            'gift_image' => $giftData['image'],
                            'gift_type' => $giftData['gift_type'],
                            'gift_num' => $giftNum,
                            'change_timestamp' => $now,
                            'room_id' => $roomId,
                            'type' => $placeType
                        ];
                        $streamId = $this->giftModel->addStream($streamLog);
                        $streamLog['stream_id'] = $streamId;
                        $streamLog['base_gift_price'] = $giftPrice;
                        $streamLog['wealth_num'] = $giftData['wealth_num'];//自定义富豪值
                        $streamList[] = $streamLog;
                        //套盒内包含的礼物
                        foreach($giftData['ext_data'] as $extGift) {
                            $streamLog = [
                                'user_id' => $toUserId,
                                'from_user_id' => $fromUserId,
                                'gift_id' => $extGift['gift_id'],
                                'gift_name' => $extGift['name'],
                                'gift_price' => 0,
                                'gift_image' => $extGift['image'],
                                'gift_type' => $extGift['gift_type'],
                                'gift_num' => $giftNum,
                                'change_timestamp' => $now,
                                'room_id' => $roomId,
                                'type' => $placeType
                            ];
                            $streamLog['stream_id'] = $streamId;
                            $streamLog['base_gift_price'] = 0;
                            $streamLog['wealth_num'] = 0;//自定义富豪值
                            $streamLog['hide_msg'] = 1;//是否隐藏页面信息
                            $streamList[] = $streamLog;
                        }
                    }
                    //热度卡处理
                    if($giftData['gift_type'] == 10){
                        //获取房间记录id
                        $roomOpenId = $this->roomModel->getRoomOpenList($roomId, 'roomOpenId');
                        if(empty($roomOpenId)) {
                            continue;
                        }
                        //获取房间开启记录
                        $openLog = $this->roomModel->getRoomOpenLog($roomOpenId);

                        //记录热度卡送出记录
                        $finalHotNum = $giftNum * $giftData['hot_num'];
                        $insert = [
                            'room_id' => $roomId,
                            'gift_id' => $giftId,
                            'user_id' =>  $toUserId,
                            'from_user_id' => $fromUserId,
                            'hot_num' => $finalHotNum,
                            'gift_num' => $giftNum,
                            'gift_stream_id' => $streamId,
                            'open_room_log_id' => $openLog['id'],
                            'created_at' => date('Y-m-d H:i:s',$now)
                        ];
                        $this->giftModel->insertHotGiftCard($insert);
                    }
                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollBack();
                    $flag = 1;
                    $error_res[] = ['gift_id'=>$giftId, 'gift_num'=>$giftNum, 'error'=>'新增流水失败'];
                    continue;
                }
                if(empty($streamList)) {
                    continue;
                }
                //金币
                $this->handleKkBalance($streamList, $roomId, $roomInfo);

                //发送消息
                //$this->handleSendMsg($placeType, $roomId, $fromUserId, $streamList, $giftData, $giftNum);

                //MQ
                $this->handleMq(1, $streamList);

                //房间流水
                $this->handleRoomWealthBalance($streamList, $is_certified);
                //财富值
                $this->handleWealthBalance($streamList);
                //魅力值
		$this->handleCharmBalance($streamList);

		//发送消息
		$this->handleSendMsg($placeType, $roomId, $fromUserId, $streamList, $giftData, $giftNum);

                //主播收礼排行榜
                $this->handleAnchorAcceptGiftRank($streamList);

                //房间团战
                $this->handleGame($streamList);
                //跨房PK
                $this->handCrossRoomPkHandleGame($streamList,$giftData);
                //幸运礼物抽奖
                if($giftData['gift_type'] == 2) {
                    $this->handleLuckGift($streamList, $giftData, $giftNum, $fromUserId, $roomId);
                }
                //新幸运礼物抽奖
                if($giftData['gift_type'] == 7) {
                    //送礼消耗钻石数 总计
                    $diamondNumAll = $giftData['price'] * $giftNum * count($toUserIds);
                    $this->handleLuckGiftV2($diamondNumAll, $giftData, ($giftNum*count($toUserIds)), $fromUserId, $roomId);
                }
                //商品礼物处理
                if($giftData['gift_type'] == 11) {
                    $this->handleGiftGoods($giftData, $giftNum, $fromUserId, $toUserIds, $roomId);
                }
                //拍拍房处理
                if(!empty($roomId)) {
                    $this->doRoomPaiPai($roomId, $roomInfo, $streamList);
                }
                //用户礼物数量统计
                $this->handleUserGiftStatistics($streamList);

                $giftBatchMsgData['gift_list'][] = ['gift_id'=>$giftId, 'gift_num'=>$giftNum, 'gift_name'=>$giftData['name']];
                $giftBatchMsgData['diamond_num'] = $giftBatchMsgData['diamond_num'] + ($val['gift_num']*$giftData['price']);
            }

            //更新
            if($flag == 1) {
                $this->giftModel->updateGiftSendBatch($batchId, ['status'=>9, 'error_res'=>json_encode($error_res)]);
            }else{
                $this->giftModel->updateGiftSendBatch($batchId, ['status'=>2]);
            }

            //守护礼物不触发消息推送
            if($giftData['gift_type'] != 8){
                $this->msgService->giftbagbatchMsg($toUserId, $fromUserId, $giftBatchMsgData['diamond_num'].'钻石', $giftBatchMsgData['gift_list']);
            }

        } while (false);
    }
    //校验基本参数
    protected function checkParam($fromUserId, $toUserIds, $giftId, $giftNum, $roomId) {
        $code = Hint::SUCCESS;
        $msg = '';
        do {
            if(empty($fromUserId)) {
                $code = Hint::LOGIN_OUT;
                break;
            }
            if (empty($toUserIds) || !is_array($toUserIds) || empty($giftId)){
                $code = Hint::PARAM_ERROR;
                $msg = '赠送礼物固定参数为空或不是数字';
                break;
            }
            if($giftNum <= 0) {
                $code = Hint::PARAM_ERROR;
                $msg = '数量不能为负数';
                break;
            }
            if (in_array($fromUserId, $toUserIds)) {
                //$code = Hint::ERR_PARAMS_CHECK_FAIL;
                //$msg = '不能将礼物送给自己';
                //break;
            }
        } while (false);

        return ['code'=>$code, 'message'=>$msg, 'data'=>[]];
    }
    //校验收礼用户账户是否异常
    protected function checkParamAbnormal($abnormal, $toUserIds) {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if (!empty($abnormal)) {
                $checkAbnormalUserResult = $this->giftService->checkAbnormalUser($toUserIds);
                if ($checkAbnormalUserResult['code'] != Hint::SUCCESS) {
                    $code = $checkAbnormalUserResult['code'];
                    $data = $checkAbnormalUserResult['data'];
                    break;
                }
            }
        } while (false);

        return ['code'=>$code, 'message'=>$msg, 'data'=>$data];
    }
    //获取礼物数据
    protected function getGiftInfo($placeType, $giftId, &$giftData) {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            $giftInfo = $this->giftModel->getGift(['gift_id' => $giftId], ['gift_id', 'name', 'image', 'price', 'gift_type', 'classification', 'ext_data', 'wealth_num','hot_num','need_wealth_rank']);
            if (empty($giftInfo)) {
                $code = Hint::THROWING_GIFT_BAG_NOT_ENOUGH;
                $msg = '礼物数据不存在';
                break;
            }
            //幸运礼物
            if($placeType==2 && $giftInfo['gift_type']==2) {
                $code = Hint::THROWING_GIFT_BAG_NOT_ENOUGH;
                $msg = '礼物来源非法,不可从背包赠送';
                break;
            }

            $giftInfo['ext_data'] = json_decode($giftInfo['ext_data'], true);
            //盲盒礼物
            if($giftInfo['gift_type']==3) {
                if(empty($giftInfo['ext_data'])) {
                    $code = Hint::ERR_SYS_FAIL;
                    $msg = '礼物信息异常';
                    break;
                }
                $multiple = 10000;//万分
                foreach($giftInfo['ext_data'] as $k=>$v) {
                    $giftInfo['ext_data'][$k] = round($v/$multiple, 4);
                }
            }
            //富豪值礼物
            if($giftInfo['gift_type'] == 4) {
                $giftInfo['price'] = 0;
            }
            //套盒礼物
            if($giftInfo['gift_type'] == 6) {
                $extData = [];
                if(!empty($giftInfo['ext_data'])) {
                    $extGiftList = $this->giftModel->getGiftByGiftIds($giftInfo['ext_data'], ['gift_id', 'name', 'image', 'price', 'gift_type', 'classification', 'ext_data', 'wealth_num']);
                    $extGiftList = array_column($extGiftList, null, 'gift_id');
                    foreach($giftInfo['ext_data'] as $val) {
                        if(empty($extGiftList[$val])) {
                            continue;
                        }
                        if($extGiftList[$val]['gift_type'] != 1) {
                            continue;
                        }
                        $extData[] = $extGiftList[$val];
                    }
                }
                $giftInfo['ext_data'] = $extData;
            }

            $giftData = $giftInfo;

        } while (false);

        return ['code'=>$code, 'message'=>$msg, 'data'=>$data];
    }
    //校验背包数量
    protected function checkBagNum($fromUserId, $toUserIds, $giftId, $giftNum) {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            $needNum = $giftNum * count($toUserIds);
            //背包礼物
            $giftBagData = $this->giftBagModel->get(['user_id' => $fromUserId, 'gift_id' => $giftId], true);
            $avail = empty($giftBagData['avail']) ? 0 : $giftBagData['avail'];
            if(empty($needNum) || empty($avail) || $avail<$needNum) {
                $code = Hint::THROWING_GIFT_BAG_NOT_ENOUGH;
                $msg = '礼物数量不足';
                break;
            }

        } while (false);

        return ['code'=>$code, 'message'=>$msg, 'data'=>$data];
    }
    //校验账户余额
    protected function checkUserDiamondWallet($fromUserId, $diamondNumAll) {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            //用户账户
            $walletInfo = $this->walletModel->get_wallet($fromUserId);
            $diamondBalance = empty($walletInfo['diamond_balance']) ? 0 : $walletInfo['diamond_balance'];
            if($diamondBalance < $diamondNumAll) {
                $code = Hint::DIAMOND_NOT_ENOUGH;
                break;
            }

        } while (false);

        return ['code'=>$code, 'message'=>$msg, 'data'=>$data];
    }
    //校验财富等级
    protected function checkWealth($fromUserId, $giftData) {
        $code = Hint::SUCCESS;
        $msg = '';
        $data = [];
        do {
            if(empty($giftData['need_wealth_rank'])) {
                break;
            }

            //获取用户财富值
            $userWallet = $this->walletModel->get_wallet($fromUserId);
            $userWealthBalance = empty($userWallet['wealth_balance']) ? 0 : $userWallet['wealth_balance'];

            //财富等级
            $wealthRankList = $this->financeWealthModel->getWealthRankData();
            $userWealthRankLevel = 0;
            $rankName = '';
            foreach($wealthRankList as $val) {
                if($val['min_value']<=$userWealthBalance && $userWealthBalance<=$val['max_value']) {
                    $userWealthRankLevel = $val['level'];
                }
                if($val['level'] == $giftData['need_wealth_rank']) {
                    $rankName = $val['rank_name'];
                }
            }

            if($giftData['need_wealth_rank'] > $userWealthRankLevel) {
                $code = Hint::PARAM_ERROR;
                $msg = '此礼物需财富等级达到 '.$rankName.' 级';
                break;
            }

        } while (false);

        return ['code'=>$code, 'message'=>$msg, 'data'=>$data];
    }

    //房间流水
    protected function handleRoomWealthBalance($streamList, $is_certified) {
        DB::beginTransaction();
        try {
            foreach($streamList as $val) {
                if(in_array($val['gift_type'], [5,9])) {
                    continue;
                }
                $giftPrice = $val['base_gift_price'];
                //用计算后的礼物价值
                if(in_array($val['gift_type'], [2, 3, 7])) {
                    $giftPrice = $val['gift_price'];
                }
                if($giftPrice <= 0) {
                    continue;
                }
                $roomWealthValue = intval($giftPrice * $val['gift_num'] * ($this->ratioConf['diamond_to_room_wealth'] ?? 1));

                $this->financeRoomWealthModel->inc($val['from_user_id'], $val['user_id'], $val['room_id'], 3, $roomWealthValue, $is_certified,0,$val['stream_id']);
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            write_log('error_sendGift', 'handleRoomWealthBalance', ['streamList'=>$streamList, 'is_certified'=>$is_certified, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
            return false;
        }
    }

    //财富值
    protected function handleWealthBalance($streamList) {
        DB::beginTransaction();
        try {
            foreach($streamList as $val) {
                if(in_array($val['gift_type'], [5,9])) {
                    continue;
                }
                //富豪值礼物
                if($val['gift_type'] == 4) {
                    $wealthTotal = $val['wealth_num'] * $val['gift_num'];
                }else{
                    $giftPrice = $val['base_gift_price'];
                    //用计算后的礼物价值
                    if(in_array($val['gift_type'], [2, 7])) {
                        $giftPrice = $val['gift_price'];
                    }
                    $wealthTotal = intval($giftPrice * $val['gift_num'] * ($this->ratioConf['diamond_to_wealth'] ?? 1));    
                }
                if($wealthTotal <= 0) {
                    continue;
                }

                $this->financeWealthModel->inc($val['from_user_id'], $val['user_id'], $val['room_id'], 0, $wealthTotal, '聊天室打赏-收获财富值',0,$val['stream_id']);
                //用户送礼增加排行榜值
                if($val['gift_type'] != 8){
                    $this->roomProtectServices->incProtectRank($val['user_id'],$wealthTotal,$val['room_id']);
                } 
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            write_log('error_sendGift', 'handleWealthBalance', ['streamList'=>$streamList, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
            return false;
        }
    }
    //魅力值
    protected function handleCharmBalance($streamList) {
        DB::beginTransaction();
        try {
            foreach($streamList as $val) {
                if(in_array($val['gift_type'], [5,9])) {
                    continue;
                }
                $giftPrice = $val['base_gift_price'];
                //用计算后的礼物价值
                if(in_array($val['gift_type'], [2, 3, 7])) {
                    $giftPrice = $val['gift_price'];
                }
                if($giftPrice <= 0) {
                    continue;
                }
                $charmTotal = intval($giftPrice * $val['gift_num'] * ($this->ratioConf['diamond_to_charm'] ?? 1));

                $this->financeCharmModel->inc($val['user_id'], $val['from_user_id'], $val['room_id'], 0, $charmTotal, ($this->descConf['room_gift_receive_charm'] ?? ''),0, $val['stream_id']);
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            write_log('error_sendGift', 'handleCharmBalance', ['streamList'=>$streamList, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
            return false;
        }
    }
    //金币
    protected function handleKkBalance($streamList, $roomId, $roomInfo) {
        $now = time();
        //拍拍房
        $inPaipai = 0;
        do {
            if(!empty($roomId) && !empty($roomInfo) && $roomInfo['room_type']["id"]==46) {
                //是否进行中
                $cacheKey = $this->roomPaiPaiKey.$roomId;
                $info = Redis::HGETALL($cacheKey);
                if(empty($info)) {
                    break;
                }
                if($info['status']!=1 || (strtotime($info['created_at'])+$info['second_num'])<$now) {
                    break;
                }
                $inPaipai = 1;
            }
        } while (false);

        DB::beginTransaction();
        try {
            foreach($streamList as $val) {
                if(in_array($val['gift_type'],[4,5,9])) {
                    continue;
                }
                $giftPrice = $val['base_gift_price'];
                //用计算后的礼物价值
                if(in_array($val['gift_type'], [2, 3, 7])) {
                    $giftPrice = $val['gift_price'];
                }
                if($giftPrice <= 0) {
                    continue;
                }
                //收礼用户是主播 公会对公结算
                //获取用户对应对公结算公会的会长ID
                $unionUserId = $this->unionModel->getSettleUnionUserIdByUserId($val['user_id']);

                $diamondTotal = intval($giftPrice * $val['gift_num']);//总钻石
                $kkUserCacheIncrList = [];
                //金币
                if($unionUserId > 0) {
                    if(!empty($roomId)) {
                        $kk_type = 11;
                        $kk_desc = $this->descConf['kk_room_get_gift'];
                    } else {
                        $kk_type = 12;
                        $kk_desc = $this->descConf['kk_get_gift'];
                    }
                    $config=$this->systemConfigModel->getDefaultSystemConfig();
                    //用户分成比例
                    $rate = $config['charm_to_kk']['value'];
                    $kkTotal = intval($giftPrice * $val['gift_num'] * ($rate ?? 1));


                    $this->financeKk_Model->inc($unionUserId, $val['user_id'], $val['room_id'], $kk_type, $kkTotal, $kk_desc);
                    //零钱凑整
                    $kkUserCacheIncrList = $this->giftService->kkUserCacheIncr($diamondTotal,$rate,$kkTotal,$unionUserId);
                }else{
                    if(!empty($roomId)) {
                        $kk_type = 0;
                        $kk_desc = $this->descConf['room_gift_receive_kk'];
                    } else {
                        $kk_type = 0;
                        $kk_desc = $this->descConf['gift_receive_kk'];
                    }
                    //对私方法处理
                    //查看收礼主播是否是对私结算,若是的话按照分成比例结算
                    $res = $this->giftService->privateUnionUserReward($val['user_id'],$diamondTotal,$val['room_id']);
                    $kkTotal = $res['kktotal'];
                    $this->financeKk_Model->inc($val['user_id'], $val['from_user_id'], $val['room_id'], $kk_type, $kkTotal, $kk_desc);
                    //零钱凑整
                    $kkUserCacheIncrList = $this->giftService->kkUserCacheIncr($diamondTotal,$res['rate'],$kkTotal,$val['user_id']);
                }

                //金币零钱凑整到账
                $this->giftService->kkUserCacheHandle($kkUserCacheIncrList, $roomId);

                //公会奖励
                $this->giftService->sendGiftUnionReward($val['room_id'], $giftPrice, $val['from_user_id'], $val['user_id'], 2, $val['gift_id'], $val['gift_num'], $inPaipai);
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            write_log('error_sendGift', 'handleKkBalance', ['streamList'=>$streamList, 'file'=>$e->getFile(), 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
            return false;
        }
    }
    //房间团战
    protected function handleGame($streamList) {
        try {
            foreach($streamList as $val) {
                if(in_array($val['gift_type'], [4,5,9])) {
                    continue;
                }
                $giftPrice = $val['base_gift_price'];
                //用计算后的礼物价值
                if(in_array($val['gift_type'], [2, 3, 7])) {
                    $giftPrice = $val['gift_price'];
                }
                if($giftPrice <= 0) {
                    continue;
                }
                $diamondTotal = intval($giftPrice * $val['gift_num']);//总钻石

                if(!empty($val['room_id']) && $val['room_id']>0) {
                    $this->gameService->roomSendGiftForGameHandle($val['room_id'], $val['from_user_id'], [$val['user_id']], $val['gift_num'], $diamondTotal);
                }
            }
        } catch (\Exception $e) {
            write_log('error_sendGift', 'handleGame', ['streamList'=>$streamList, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
            return false;
        }
    }
    //跨房PK
    protected function handCrossRoomPkHandleGame($streamList,$giftData){
        try {
            foreach($streamList as $val) {
                if(in_array($val['gift_type'], [4,5,9])) {
                    continue;
                }
                $giftPrice = $val['base_gift_price'];
                //用计算后的礼物价值
                if(in_array($val['gift_type'], [2, 3, 7])) {
                    $giftPrice = $val['gift_price'];
                }
                if($giftPrice <= 0) {
                    continue;
                }
                $diamondTotal = intval($giftPrice * $val['gift_num']);//总钻石

                if(!empty($val['room_id']) && $val['room_id']>0) {
                    $this->crossRoomService->crossRoomPkGiftForGameHandle($val['room_id'], $val['from_user_id'], [$val['user_id']], $val['gift_num'], $diamondTotal,$val['stream_id'],$giftData);
                }
            }
        } catch (\Exception $e) {
            write_log('error_sendGift', 'handleCrossPkGame', ['streamList'=>$streamList, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
            return false;
        }
    }
    //幸运礼物抽奖
    protected function handleLuckGift($streamList, $giftData, $giftNum, $fromUserId, $roomId) {
        try {
            $streamIds = array_column($streamList, 'stream_id');
            $luckLogs = $this->_luckGiftSendHandle($giftData['gift_id'], $giftNum, $streamIds, $fromUserId, $roomId);
            if(!empty($luckLogs) && !empty($roomId)) {
                $lgm = array_sum(array_column($luckLogs,'multiple_num'));
                $this->roomMsgService->luckGiftMsg($roomId, $fromUserId, $giftData['gift_id'], $giftNum, $lgm);
            }
        } catch (\Exception $e) {
            write_log('error_sendGift', 'handleLuckGift', ['streamList'=>$streamList, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
            return false;
        }
    }
    //幸运礼物赠送处理
    protected function _luckGiftSendHandle($giftId, $giftNum, $streamIds, $userId, $roomId)
    {
        //万分
        $multiple = 10000;
        $diamond_desc = $this->descConf['diamond_gift_luck'];
        //日志
        $logs = [];
        do {
            $errorLog = [$giftId, $giftNum];
            if(empty($giftId)) {
                write_log('error_luckGift', '数据缺失 giftId', $errorLog);
                break;
            }
            if(empty($giftNum)) {
                write_log('error_luckGift', '数据缺失 giftNum', $errorLog);
                break;
            }
            //获取奖池
            $giftLuckPool = $this->giftModel->getGiftLuckPoolByGiftId($giftId);
            if(empty($giftLuckPool)) {
                write_log('error_luckGift', '数据缺失 giftLuckPool', $errorLog);
                break;
            }
            $giftLuckPoolMap = array_column($giftLuckPool, null, 'multiple_num');
            if(count($giftLuckPool) != count($giftLuckPoolMap)) {
                write_log('error_luckGift', '数据异常 幸运礼物奖池倍数存在重复', $errorLog);
                break;
            }
            $rateSum = array_sum(array_column($giftLuckPool, 'base_rate'));
            if($rateSum != 10000) {
                write_log('error_luckGift', '数据异常 幸运礼物奖池总概率不是100%', $errorLog);
                break;
            }
            $baseRateMap = [];
            foreach($giftLuckPool as $val) {
                $baseRateMap[$val['multiple_num']] = round($val['base_rate']/$multiple, 4);
            }

            //每一次都要重新计算
            foreach($streamIds as $streamId) {
                for($i=1;$i<=$giftNum;$i++) {
                    $multipleNum = probabilityAlgorithm($baseRateMap);
                    $poolInfo = $giftLuckPoolMap[$multipleNum];

                    $item = [];
                    $item['gift_id'] = $giftId;
                    $item['gift_num'] = $giftNum;
                    $item['stream_id'] = $streamId;
                    $item['user_id'] = $userId;
                    $item['draw_no'] = $i;
                    $item['multiple_num'] = $poolInfo['multiple_num'];
                    $item['diamond_num'] = $poolInfo['diamond_num'];
                    $item['base_rate'] = $poolInfo['base_rate'];

                    $logs[] = $item;
                }
            }

            //计算奖励钻石数
            $diamondNumAll = array_sum(array_column($logs, 'diamond_num'));

            DB::beginTransaction();
            try {
                //记录幸运礼物流水
                $this->giftModel->addGiftLuckLog($logs);
                //钻石变更
                if($diamondNumAll > 0) {
                    $this->diamondModel->inc($userId, 0, $roomId, 11, $diamondNumAll, $diamond_desc);
                }

                DB::commit();
            } catch (\Exception $e) {
                $logs = [];
                DB::rollBack();
                write_log('error_luckGift', '数据异常 抽奖失败', [$errorLog, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
                return false;
            }
        } while (false);
        return $logs;
    }
    //新幸运礼物抽奖
    protected function handleLuckGiftV2($diamondNumAll, $giftData, $giftNum, $fromUserId, $roomId, $toUserIds = []) {
        try {
            $diamond_desc = $this->descConf['diamond_gift_luck'];
            $giftId = $giftData['gift_id'];
            $giftPrice = $giftData['price'];
            $giftName = $giftData['name'];
            //需要抽奖次数
            $needNum = $giftNum;

            //获取奖池数据
            $pool = $this->giftModel->getLuckGiftPool();
            $poolList = [];//已开启的奖池
            foreach($pool as $val) {
                if($val['gift_price'] != $giftPrice) {
                    continue;
                }
                if($val['status'] == 1){
                    $poolList[] = $val;
                }
            }
            if(empty($poolList)) {
                write_log('error_luckGift', 'handleLuckGiftV2 无开启奖池', [$diamondNumAll, $giftId, $giftNum, $fromUserId, $roomId]);
                return false;
            }

            //用户总消耗钻石数
            $diamondNumNow = $diamondNum = $this->giftModel->getUserLuckGiftDiamondNumByWeek($fromUserId);

            //白名单
            $whiteListNow = $whiteList = $this->giftModel->getLuckGiftWhite($fromUserId);

            //抽奖
            $drawLogList = [];//抽奖明细
            $whiteUpList = [];//使用了的白名单
            $rewardDiamondNumAll = 0;//奖励钻石总计
            $winList = [];
            try {
                for($i=1;$i<=$needNum;$i++) {
                    $diamondNumNow = $diamondNumNow + $giftPrice;
                    $drawLog = [];
                    $drawLog['draw_no'] = $i;
                    $drawLog['white_id'] = 0;
                    $drawLog['pool_id'] = 0;
                    $drawLog['r_diamond_num'] = 0;
                    //白名单
                    if(!empty($whiteListNow)) {
                        $whiteInfo = array_shift($whiteListNow);
                        $drawLog['r_diamond_num'] = $whiteInfo['diamond_num'];
                        $drawLog['white_id'] = $whiteInfo['id'];
                        $whiteUpList[] = $whiteInfo['id'];
                    }else{
                        $usePool = [];//使用的奖池
                        //在范围的
                        foreach($poolList as $val) {
                            if($val['min_num']<=$diamondNumNow && $diamondNumNow<=$val['max_num']) {
                                $usePool = $val;
                            }
                        }
                        //上一个
                        $prevNum = 0;
                        if(empty($usePool)) {
                            foreach($poolList as $val) {
                                if($val['max_num']<=$diamondNumNow && $prevNum<=$val['max_num']) {
                                    $usePool = $val;
                                    $prevNum = $val['max_num'];
                                }
                            }
                        }
                        //下一个
                        $nextNum = 0;
                        if(empty($usePool)) {
                            foreach($poolList as $val) {
                                if($val['min_num']>=$diamondNumNow && ($nextNum==0 || $nextNum>=$val['min_num'])) {
                                    $usePool = $val;
                                    $nextNum = $val['min_num'];
                                }
                            }
                        }
                        //还是没有取第一个
                        if(empty($usePool)) {
                            $usePool = $poolList[0];
                        }

                        //抽取
                        $drawLog['r_diamond_num'] = $this->giftModel->drawLuckGift($usePool['id']);
                        $drawLog['pool_id'] = $usePool['id'];
                    }

                    $drawLogList[] = $drawLog;

                    if ($drawLog['r_diamond_num'] > 0 && !empty($toUserIds) && isset($toUserIds[$i-1])) {
                        $winList[] = ['num' => $drawLog['r_diamond_num'], 'uid' => $toUserIds[$i-1]];
                    }
                }
            } catch (\Exception $e) {
                write_log('error_luckGift', 'handleLuckGiftV2 抽奖失败', [$diamondNumAll, $giftId, $giftNum, $fromUserId, $roomId, 'message'=>$e->getMessage(), 'line'=>$e->getLine()]);
                return false;
            }
            $rewardDiamondNumAll = array_sum(array_column($drawLogList, 'r_diamond_num'));

            //抽奖保存
            DB::beginTransaction();
            try {
                //新增新幸运礼物抽奖记录
                $log = [];
                $log['user_id'] = $fromUserId;
                $log['gift_id'] = $giftId;
                $log['gift_num'] = $giftNum;
                $log['u_diamond_num'] = $diamondNumAll;
                $log['r_diamond_num'] = $rewardDiamondNumAll;
                $log['r_list'] = json_encode($drawLogList);
                $logId = $this->giftModel->addLuckGiftDrawLog($log);

                //白名单
                foreach($whiteUpList as $whiteId) {
                    $this->giftModel->updateLuckGiftWhite($whiteId, $logId);
                }

                //钻石变更
                if($rewardDiamondNumAll > 0) {
                    $this->diamondModel->inc($fromUserId, 0, $roomId, 11, $rewardDiamondNumAll, $diamond_desc);
                }

                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                write_log('error_luckGift', 'handleLuckGiftV2 抽奖保存', [$diamondNumAll, $giftId, $giftNum, $fromUserId, $roomId, 'message'=>$e->getMessage(), 'line'=>$e->getLine()]);
                return false;
            }

            //累加新幸运礼物用户总消耗钻石数
            $this->giftModel->incrUserLuckGiftDiamondNumByWeek($fromUserId, $diamondNumAll);

            $sendUser = $this->userService->getUserData($fromUserId);

            $is_sound = '1';
//            if ($rewardDiamondNumAll > bcmul($diamondNumAll, 1)) {
//                $is_sound = '1';
//            }
            $multiple = (string)bcdiv($rewardDiamondNumAll, $diamondNumAll, 1);

            //发信息
//            if($roomId > 0) {
//                $this->roomMsgService->luckGiftMsgV2($roomId, $fromUserId, $giftName, $giftNum, $rewardDiamondNumAll, $sendUser['nickname'], $multiple, $is_sound);
//            }

            $giftDisplayNum = 1;

            $winRes = [];
            if (!empty($winList)) {
                $winU = array_column($winList, 'uid');
                $toUserList = $this->model_user->get_users_by_ids($winU);
                $toUserMap = array_column($toUserList, 'nickname', 'user_id');
                foreach ($winList as $win) {
                    $winRes[] = ['win_num' => $win['num'], 'nickname' => $toUserMap[$win['uid']] ?? ''];
                }
            }

            // 转运频道消息
            if ($rewardDiamondNumAll > 2000) {
                $this->msgService->luckGiftWorldMsg($fromUserId, $giftName, $giftDisplayNum, $rewardDiamondNumAll, $sendUser['nickname'], $multiple, $is_sound, $winRes);
            }

            //飘屏
            if ($rewardDiamondNumAll > 10000) {
                $actionParam = ['roomId'=>$roomId];
                $this->msgService->sendFullScreen(65 ,null,['name'=>$sendUser['nickname'], 'giftName'=>$giftName, 'giftNum'=>$giftDisplayNum, 'diamondNum'=>$rewardDiamondNumAll, 'multiple' => $multiple ],$actionParam, ['giftPrice' => $rewardDiamondNumAll]);
            }

            //飘屏
//            if($rewardDiamondNumAll > 500) {
//                $actionParam = ['roomId'=>$roomId];
//                $this->msgService->sendFullScreen(65 ,null,['name'=>$sendUser['nickname'], 'giftName'=>$giftName, 'giftNum'=>$giftNum, 'diamondNum'=>$rewardDiamondNumAll, 'multiple' => $multiple ],$actionParam);
//            }

        } catch (\Exception $e) {
            write_log('error_sendGift', 'handleLuckGift', [$diamondNumAll, $giftId, $giftNum, $fromUserId, $roomId, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
            return false;
        }
    }
    //拍拍房处理
    protected function doRoomPaiPai($roomId, $roomInfo, $streamList) {
        $now = time();
        try {
            if(empty($roomId) || empty($roomInfo) || $roomInfo['room_type']["id"]!=46) {
                return false;
            }
            //是否进行中
            $cacheKey = $this->roomPaiPaiKey.$roomId;
            $info = Redis::HGETALL($cacheKey);
            if(empty($info)) {
                return false;
            }
            if($info['status']!=1 || (strtotime($info['created_at'])+$info['second_num'])<$now) {
                return false;
            }
            //房间麦位
            $microList = $this->roomMicroModel->getRoomMicroList($roomId);

            foreach($streamList as $val) {
                if(in_array($val['gift_type'], [4,5,9])) {
                    continue;
                }
                $giftPrice = $val['base_gift_price'];
                //用计算后的礼物价值
                if(in_array($val['gift_type'], [2, 3, 7])) {
                    $giftPrice = $val['gift_price'];
                }
                if($giftPrice <= 0) {
                    continue;
                }
                $diamondTotal = intval($giftPrice * $val['gift_num']);//总钻石

                //同阵营不统计心动值
                $fromMicroId = -1;
                $toMicroId = -1;
                foreach($microList as $k1=>$v1) {
                    if($v1 == $val['from_user_id']) {
                        $fromMicroId = $k1;
                    }
                    if($v1 == $val['user_id']) {
                        $toMicroId = $k1;
                    }
                }
                if($toMicroId < 0) {
                    continue;
                }
                if(in_array($fromMicroId, [1,3,5]) && in_array($toMicroId, [1,3,5])) {
                    continue;
                }
                if(in_array($fromMicroId, [2,4,6]) && in_array($toMicroId, [2,4,6])) {
                    continue;
                }

                //拍拍房收礼送礼用户排行
                $cacheKey1 = $this->roomPaiPaiUserRankKey.$info['logId'];
                Redis::ZINCRBY($cacheKey1, $diamondTotal, min($val['from_user_id'], $val['user_id']).'|'.max($val['from_user_id'], $val['user_id']));
                Redis::EXPIRE($cacheKey1, 86400);
            }

            //拍拍房处理麦位变化并通知
            $requestData = [
                'queue_route' => 'global.roompaipai',
                'data' => [
                    'room_id' => $roomId,
                ],
            ];
            $publishObject = Publisher::getInstance();
            $publishObject->requestData = $requestData;
            $publishObject->publisher();

        } catch (\Exception $e) {
            write_log('error_sendGift', 'doRoomPaiPai', ['streamList'=>$streamList, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
            return false;
        }
    }
    //商品礼物处理
    protected function handleGiftGoods($giftData, $giftNum, $fromUserId, $toUserIds, $roomId) {
        do {
            $now = time();
            $flag = 0;
            $logList = [];
            $msgList = [];
            foreach($giftData['ext_data'] as $extGift) {
                if(empty($extGift['goods_id']) || empty($extGift['day'])) {
                    $flag = 1;
                    write_log('error_sendGift', 'handleGiftGoods 配置错误', [$giftData, $giftNum, $fromUserId, $toUserIds, $roomId]);
                    break;
                }
                $goodInfo = $this->mallModel->get_goods($extGift['goods_id']);
                if(empty($goodInfo)) {
                    $flag = 1;
                    write_log('error_sendGift', 'handleGiftGoods 配置商品不存在', [$giftData, $giftNum, $fromUserId, $toUserIds, $roomId]);
                    break;
                }
                $timeLimit = $giftNum * $extGift['day'] * 86400;
                //整理数据
                foreach($toUserIds as $toUserId) {

                    $logList[] = [
                        'user_id' => $fromUserId,
                        'to_user_id' => $fromUserId,
                        'goods_id' => $extGift['goods_id'],
                        'goods_name' => $goodInfo['goods_name'],
                        'goods_type' => $goodInfo['goods_type'],
                        'sku_id' => 0,
                        'time_limit' => $timeLimit,
                        'price' => 0,
                        'end_time' => $timeLimit,
                        'create_time' => $now,
                        'act_type' => 1,
                    ];

                    $logList[] = [
                        'user_id' => $fromUserId,
                        'to_user_id' => $toUserId,
                        'goods_id' => $extGift['goods_id'],
                        'goods_name' => $goodInfo['goods_name'],
                        'goods_type' => $goodInfo['goods_type'],
                        'sku_id' => 0,
                        'time_limit' => $timeLimit,
                        'price' => 0,
                        'end_time' => $timeLimit,
                        'create_time' => $now,
                        'act_type' => 2,
                    ];

                    $msgList[$fromUserId] = isset($msgList[$fromUserId]) ? ($msgList[$fromUserId].'、'.$goodInfo['goods_name'].'*'.$extGift['day']*$giftNum.'天') : ('您送出礼物'.$giftData['name'].'，获得'.$goodInfo['goods_name'].'*'.$extGift['day']*$giftNum.'天');
                    $msgList[$toUserId] = isset($msgList[$toUserId]) ? ($msgList[$toUserId].'、'.$goodInfo['goods_name'].'*'.$extGift['day']*$giftNum.'天') : ('恭喜您收到礼物'.$giftData['name'].'，获得'.$goodInfo['goods_name'].'*'.$extGift['day']*$giftNum.'天');
                }
            }
            if($flag || empty($logList)) {
                break;
            }

            //保存
            DB::beginTransaction();
            try {
                foreach($logList as $val) {

                    $res = $this->mallModel->shoppingAct(
                        $val['user_id'],
                        $val['to_user_id'],
                        $val['goods_id'],
                        $val['goods_name'],
                        $val['goods_type'],
                        $val['sku_id'],
                        $val['time_limit'],
                        $val['price'],
                        $val['end_time'],
                        $val['create_time'],
                        $val['act_type'],
                    );
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                write_log('error_sendGift', 'handleGiftGoods', [$giftData, $giftNum, $fromUserId, $toUserIds, $roomId, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
                return false;
            }

            //发消息
            foreach($msgList as $key=>$val) {
                $this->msgService->send_sys_text_msg($key, $val);
            }

        } while (false);
    }

    //MQ通知
    protected function handleMq($type, $streamList) {
        try {
            foreach($streamList as $val) {
                if(in_array($val['gift_type'], [9])) {
                    continue;
                }
                if(isset($val['hide_msg']) && $val['hide_msg']==1) {
                    continue;
                }
                $giftPrice = $val['base_gift_price'];
                //用计算后的礼物价值
                if(in_array($val['gift_type'], [2, 3, 7])) {
                    $giftPrice = $val['gift_price'];
                }

                //非彩蛋/富豪值 的礼物若为零不走mq
                if(!in_array($val['gift_type'],[4,5,10]) && $giftPrice == 0){
                    continue;
                }
                $priceTotal = intval($giftPrice * $val['gift_num']);//总钻石

                $this->MqGiftGive($type, $val['from_user_id'], [$val['user_id']], $val['gift_id'], $val['gift_num'], $val['room_id'], $priceTotal, $val);
            }

            //用户房间banner
            $userIds = array_unique(array_merge(array_column($streamList, 'from_user_id'), array_column($streamList, 'user_id')));
            $publishObject = Publisher::getInstance();
            $publishObject->requestData = [
                'queue_route'=>'global.userroombanner',
                'data'=>['user_ids'=>$userIds, 'type'=>2],
            ];
            $publishObject->publisher();

        } catch (\Exception $e) {
            write_log('error_sendGift', 'handleMq', ['streamList'=>$streamList, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
            return false;
        }
    }
    //MQ通知
    protected function MqGiftGive($type, $fromUserId, $toUserIds, $giftId, $giftNum, $roomId, $priceTotal, $streamLog =[]) {
        try {
            $requestData = [
                'queue_route' => 'global.gift.give',
                'data' => [
                    'mqtype' => 1,
                    'room_id' => $roomId,
                    'gift_id' => $giftId,
                    'user_id' => $fromUserId,
                    'to_user_id_array' => $toUserIds,
                    'gift_num' => $giftNum,
                    'create' => time(),
                    'type' => $type, // 0=礼物-购买 1=礼物-背包
                    'price_total' => $priceTotal,
                    'stream_log' => $streamLog,
                ],
            ];

            $publishObject = Publisher::getInstance();
            $publishObject->requestData = $requestData;
            $publishObject->publisher();
        } catch (\Exception $e) {
            write_log('error_mq', 'global.gift.give', ['requestData'=>$requestData]);
        }
    }

    //MQ通知送礼物异步处理
    protected function handleMqForAsyn($placeType, $fromUserId, $toUserIds, $giftNum, $is_certified, $giftData, $roomId, $streamList, $now) {
        try {
            $mqData = [
                'placeType' => $placeType,
                'fromUserId' => $fromUserId,
                'toUserIds' => $toUserIds,
                'giftNum' => $giftNum,
                'is_certified' => $is_certified,
                'giftData' => $giftData,
                'roomId' => $roomId,
                'streamList' => $streamList,
                'now' => $now,
            ];
            $key = md5(json_encode($mqData));
            Redis::SET($this->colorGiftMqKey.$key,json_encode($mqData));
            Redis::expire($this->colorGiftMqKey.$key,86400);
            $requestData = [
                'queue_route' => 'global.sendgiftasyn',
                'data' => ['mqredis'=>$key],
            ];

            $publishObject = Publisher::getInstance();
            $publishObject->requestData = $requestData;
            $publishObject->publisher();
        } catch (\Exception $e) {
            write_log('error_sendGift', 'handleMqForAsyn MQ通知送礼物异步处理', ['streamList'=>$streamList, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
            return false;
        }
    }

    //根据礼物流水发信息(新幸运礼物)
    protected function handleNewLuckGiftSendMsg($placeType, $roomId, $fromUserId, $streamList) {
        try {
            //守护麦礼物不发送通知
//            if($giftData['gift_type'] == 8) {
//                return true;
//            }

            //房间内
            if($roomId > 0) {
                //礼物总价值
                $totalPrice = 0;
                $numAll = 0;
                $popnum = 1;
                $allpop = 1;
                $colorGiftPop = [];
                $sendAllUserGift = [];
                $flat_array = [];
                foreach($streamList as $val) {
                    $giftPrice = $val['base_gift_price'];
                    //用计算后的礼物价值
                    if(in_array($val['gift_type'], [2, 3, 7])) {
                        $giftPrice = $val['gift_price'];
                    }elseif(in_array($val['gift_type'],[4,5,9])){
                        $giftPrice = 0;
                    }
                    if($giftPrice <= 0 && !in_array($val['gift_type'],[4,5,9])) {
                        continue;
                    }
                    $priceTotal = intval($giftPrice * $val['gift_num']);//总钻石
                    $totalPrice = $totalPrice + $priceTotal;
                    $numAll = $numAll + $val['gift_num'];

                }
                $toUserIdArray = array_unique(array_column($streamList, 'user_id'));
//                if($giftData['gift_type'] == 5){
//                    //处理飘屏/公屏
//                    $this->roomMsgService->colorGiftMsg($roomId, $fromUserId, $giftData['gift_id'], $giftNum, $roomInfo, $colorGiftPop, $giftData);
//                }else{
//                    //大额礼物全服飘萍
//                    if ($totalPrice >= $position['d']) {
//                        $this->msgService->all_gift($giftData['name'], $numAll, $fromUserId, $roomId, $totalPrice);
//                    }
//                }


                //根据礼物流水更新送礼物计数消息
                $this->_sendbroadcastTally($roomId, $fromUserId, $streamList);

                // 礼物消息
//                $this->_sendBroadcastGift($totalPrice, $roomId, $fromUserId, $toUserIdArray, $giftData['gift_id'], $giftNum, $giftData['price'], $sendAllUserGift);

                //套盒礼物 礼物消息
//                if($giftData['gift_type'] == 6) {
//                    foreach($giftData['ext_data'] as $extGift) {
//                        $this->_sendBroadcastGift($totalPrice, $roomId, $fromUserId, $toUserIdArray, $extGift['gift_id'], $giftNum, 0, ['hide_msg'=>1]);
//                    }
//                }

                //标记礼物数据消息
                $this->_sendMarkGift($roomId, $streamList);

                //检测用户财富等级是否变化
                $this->_checkWealthRank([$fromUserId]);

                //检测用户魅力等级是否变化
                $this->_checkCharmRank($toUserIdArray);

                //盲盒礼物公屏消息
//                if($giftData['gift_type'] == 3) {
//                    $this->_sendGiftMhMsg($streamList, $fromUserId, $roomId, $giftData);
//                }
            }
            //非房间内
//            if($roomId == 0) {
//                foreach($streamList as $val) {
//                    if(in_array($val['gift_type'],[9])){
//                        continue;
//                    }
//                    $this->msgService->give_gift($val['from_user_id'], $val['user_id'], $val['gift_id'], $val['gift_num']);
//                }
//            }
        } catch (\Exception $e) {
            write_log('error_sendNewLuckGift', 'handleNewLuckGiftSendMsg', ['streamList'=>$streamList, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
            return false;
        }
    }

    //根据礼物流水发信息
    protected function _sendNewLuckGiftBroadcastGift($streamList, $roomId, $fromUserId, $toUserIdArray, $giftData, $giftNum) {
        try {
//            $position = config('animation.position');

            //房间内
            if($roomId > 0) {
                //礼物总价值
                $totalPrice = 0;
                $numAll = 0;
                $popnum = 1;
                $allpop = 1;
                $colorGiftPop = [];
                $sendAllUserGift = [];
                $flat_array = [];
                foreach ($streamList as $val) {
                    $giftPrice = $val['gift_price'];
                    $priceTotal = intval($giftPrice * $val['gift_num']);//总钻石
                    $totalPrice = $totalPrice + $priceTotal;
                    $numAll = $numAll + $val['gift_num'];

                }

                // 礼物消息
                $this->_sendBroadcastGift($totalPrice, $roomId, $fromUserId, $toUserIdArray, $giftData['gift_id'], $giftNum, $giftData['price'], $sendAllUserGift);
            }

            return true;

        } catch (\Exception $e) {
            write_log('error_sendNewLuckGift', '_sendNewLuckGiftBroadcastGift', ['streamList'=>$streamList, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
            return false;
        }
    }

    //根据礼物流水发信息
    protected function handleSendMsg($placeType, $roomId, $fromUserId, $streamList, $giftData, $giftNum, $roomInfo=[]) {
        try {
            $position = config('animation.position');
            //守护麦礼物不发送通知
            if($giftData['gift_type'] == 8) {
                return true;
            }
            //房间内
            if($roomId > 0) {
                //礼物总价值
                $totalPrice = 0;
                $numAll = 0;
                $popnum = 1;
                $allpop = 1;
                $colorGiftPop = [];
                $sendAllUserGift = [];
                $flat_array = [];
                foreach($streamList as $val) {
                    $giftPrice = $val['base_gift_price'];
                    //用计算后的礼物价值
                    if(in_array($val['gift_type'], [2, 3, 7])) {
                        $giftPrice = $val['gift_price'];
                    }elseif(in_array($val['gift_type'],[4,5,9])){
                        $giftPrice = 0;
                    }
                    if($giftPrice <= 0 && !in_array($val['gift_type'],[4,5,9])) {
                        continue;
                    }
                    $priceTotal = intval($giftPrice * $val['gift_num']);//总钻石
                    $totalPrice = $totalPrice + $priceTotal;
                    $numAll = $numAll + $val['gift_num'];
                    if($giftData['gift_type'] == 5){
                        if($val['gift_type'] == 5){
                            continue;
                        }
                        $flat_array[$val['user_id']][] = $val['gift_id'];

                        // 计算一维数组中每个值的出现次数
                        $counts = array_count_values($flat_array[$val['user_id']]);
                        $colorGiftPop[$val['gift_id']] = [
                            'colorInfo' => $giftData,
                            'pop_gift_id' => $val['gift_id'],
                            'pop_num' => $counts[$val['gift_id']],
                        ];
                        $sendAllUserGift['colorInfo'] = $giftData;
                        $sendAllUserGift[$val['user_id']][$val['gift_id']] = [
                            'colorInfo' => $giftData,
                            'pop_gift_id' => $val['gift_id'],
                            'pop_num' => $counts[$val['gift_id']],
                            'gift_name' => $val['gift_name'],
                            'gift_price' => $val['gift_price']
                        ];

                    }
                }
                $toUserIdArray = array_unique(array_column($streamList, 'user_id'));
                if($giftData['gift_type'] == 5){
                    //处理飘屏/公屏
                    $this->roomMsgService->colorGiftMsg($roomId, $fromUserId, $giftData['gift_id'], $giftNum, $roomInfo, $colorGiftPop, $giftData);
                }else{
                    //大额礼物全服飘萍
                    if ($totalPrice >= $position['d']) {
                        $this->msgService->all_gift($giftData['name'], $numAll, $fromUserId, $roomId, $totalPrice);
                    }
                }
                

                //根据礼物流水更新送礼物计数消息
                $this->_sendbroadcastTally($roomId, $fromUserId, $streamList);

                // 礼物消息
                $this->_sendBroadcastGift($totalPrice, $roomId, $fromUserId, $toUserIdArray, $giftData['gift_id'], $giftNum, $giftData['price'], $sendAllUserGift);
                //套盒礼物 礼物消息
                if($giftData['gift_type'] == 6) {
                    foreach($giftData['ext_data'] as $extGift) {
                        $this->_sendBroadcastGift($totalPrice, $roomId, $fromUserId, $toUserIdArray, $extGift['gift_id'], $giftNum, 0, ['hide_msg'=>1]);
                    }
                }

                //标记礼物数据消息
                $this->_sendMarkGift($roomId, $streamList);

                //检测用户财富等级是否变化
                $this->_checkWealthRank([$fromUserId]);

                //检测用户魅力等级是否变化
                $this->_checkCharmRank($toUserIdArray);

                //盲盒礼物公屏消息
                if($giftData['gift_type'] == 3) {
                    $this->_sendGiftMhMsg($streamList, $fromUserId, $roomId, $giftData);
                }
            }
            //非房间内
            if($roomId == 0) {
                foreach($streamList as $val) {
                    if(in_array($val['gift_type'],[9])){
                        continue;
                    }
                    $this->msgService->give_gift($val['from_user_id'], $val['user_id'], $val['gift_id'], $val['gift_num']);
                }
            }
        } catch (\Exception $e) {
            write_log('error_sendGift', 'handleSendMsg', ['streamList'=>$streamList, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
            return false;
        }
    }
    //礼物消息
    protected function _sendBroadcastGift($totalPrice, $roomId, $fromUserId, $toUserIdArray, $giftId, $giftNum, $giftPrice, $extend=[]) {
        $position = config('animation.position');
        $type = 0;
        if ($totalPrice >= $position['a'] && $totalPrice < $position['b']) {
            $type = 1;  // a
        } elseif ($totalPrice >= $position['b'] && $totalPrice < $position['c']) {
            $type = 2;  // a,b
        } elseif ($totalPrice >= $position['c'] && $totalPrice < $position['d']) {
            $type = 3;  // a,b,c
        } elseif ($totalPrice >= $position['d']) {
            $type = 4;  // a,b,c,d
        }
        if($totalPrice == 0){
            $type = 1;
        }
        //特殊类型特殊处理彩蛋礼物价格低于50价格也要发消息
        if(isset($extend['colorInfo']['gift_type']) &&  $extend['colorInfo']['gift_type'] == 5 && $type == 1){
            $type = 2;
            unset($extend['colorInfo']);
        }
        $toUserIdArray = array_values(array_unique($toUserIdArray));

        // 礼物消息
        $this->roomMsgService->broadcast_gift($roomId, $fromUserId, $toUserIdArray, $giftId, $giftNum, $type, "", $giftPrice, null, null, $extend);
    }
    //标记礼物数据消息
    protected function _sendMarkGift($roomId, $streamList) {
        $this->roommicro_service = RoomServicesInit::createMicroNew($roomId);
        $this->roomhostmicro_service = RoomServicesInit::createHostMicroNew($roomId);
        foreach($streamList as $val) {
            if(in_array($val['gift_type'],[9])){
                continue;
            }
            if(isset($val['hide_msg']) && $val['hide_msg']==1) {
                continue;
            }
            //主持麦
            if ($this->roomhostmicro_service->mark_gift($val['room_id'], $val['from_user_id'], $val['user_id'], $val['gift_id'], $val['gift_num'])) {
                //发送更新消息
                $this->roomMsgService->broadcast_hostmicro_gift($val['from_user_id'], $val['room_id'], 0, $val['gift_id'], $val['gift_num']);
            }
            //普通麦
            $microId = $this->roommicro_service->mark_gift($val['room_id'], $val['from_user_id'], $val['user_id'], $val['gift_id'], $val['gift_num']);
            if ($microId !== null) {
                //发送更新消息
                $this->roomMsgService->broadcast_micro_gift($val['from_user_id'], $val['room_id'], $microId, $val['gift_id'], $val['gift_num']);
            }
        }
    }
    //根据礼物流水更新送礼物计数消息
    protected function _sendbroadcastTally($roomId, $fromUserId, $streamList) {
        $tallyData = $this->roomTallyService->incByGiftStream($roomId, $fromUserId, $streamList);
        if (!empty($tallyData)){
            $this->roomMsgService->broadcastTallyData($roomId, $tallyData['recv']);
        }
    }
    //检测用户财富等级是否变化
    protected function _checkWealthRank($userIds) {
        foreach($userIds as $userId) {
            $rank_data = $this->financeService->check_wealth_rank($userId);
            if (!empty($rank_data)) {
                $this->msgService->rank_update($userId, $rank_data['rank_name'], $rank_data['image'], $rank_data['wealth_balance']);
            }    
        }
    }
    //检测用户财富等级是否变化
    protected function _checkCharmRank($userIds) {
        foreach($userIds as $userId) {
            $rank_data = $this->financeService->check_charm_rank($userId);
            if (!empty($rank_data)) {
                $this->msgService->charm_rank_update($userId, $rank_data['rank_name'], $rank_data['image'], $rank_data['charm_balance']);
            }
        }
    }
    //盲盒礼物公屏消息
    protected function _sendGiftMhMsg($streamList, $fromUserId, $roomId, $giftData) {
        $userGift = [];
        $toUserIds = [];
        foreach($streamList as $val) {
            $userGift[$val['user_id']]['gift_num'] = empty($userGift[$val['user_id']]['gift_num']) ? 0 : $userGift[$val['user_id']]['gift_num'];
            $userGift[$val['user_id']]['gift_num'] = $userGift[$val['user_id']]['gift_num'] + $val['gift_num'];
            $userGift[$val['user_id']]['num'] = empty($userGift[$val['user_id']]['num']) ? 0 : $userGift[$val['user_id']]['num'];
            $userGift[$val['user_id']]['num'] = $userGift[$val['user_id']]['num'] + $val['gift_num']*$val['gift_price'];

            // if($val['gift_price'] > $val['base_gift_price']) {
                $toUserIds[] = $val['user_id'];
            // }
        }

        //盲盒礼物公屏消息
        $this->roomMsgService->giftMh_msg($toUserIds, $userGift, $fromUserId, $roomId, $giftData);
    }
    //飘屏
    protected function handleSendFull($fromUserId, $toUserIds, $giftData, $giftNum) {
	    do {
            try {
                if(!in_array($giftData['gift_type'], [6])){
                    break;
                }
                $userIds = array_merge($toUserIds, [$fromUserId]);
                $userList = $this->userService->getUserInfoByUserIds($userIds);
                $userList = array_column($userList, null, 'user_id');
                if(empty($userList[$fromUserId])) {
                    break;
                }

                //套盒礼物
                if($giftData['gift_type'] == 6) {
                    foreach($toUserIds as $toUserdId) {
                        if(empty($userList[$toUserdId])) {
                            continue;
                        }

                        $this->msgService->sendFullScreen(62 ,null,['name1'=>$userList[$fromUserId]['nickname'], 'name2'=>$userList[$fromUserId]['nickname'], 'giftPrice'=>$giftData['price'], 'giftName'=>$giftData['name'], 'giftNum'=>$giftNum ],[]);
                    }
                }

            } catch (\Exception $e) {
                return false;
            }
        } while (false);
    }
    //埋点
    protected function _sendTrack($roomId, $fromUserId, $toUserIds) {
        if(empty($roomId) || empty($fromUserId) || empty($toUserIds)) {
            return false;
        }
        $roomOpenId = $this->roomModel->getRoomOpenList($roomId, 'roomOpenId');
        if(empty($roomOpenId)) {
            return false;
        }

        //埋点
        $this->tdService->handleTrack('give_present', ['user_id'=>$fromUserId, 'room_id'=>$roomId, 'roomOpenId'=>$roomOpenId]);

        foreach($toUserIds as $userId) {
            //埋点
            $this->tdService->handleTrack('get_present', ['user_id'=>$userId, 'room_id'=>$roomId, 'roomOpenId'=>$roomOpenId]);
        }
        return true;
    }

    //用户礼物数量统计
    protected function handleUserGiftStatistics($streamList) {
        try {
            foreach($streamList as $val) {
                if(in_array($val['gift_type'],[9])){
                    continue;
                }
                if(isset($val['hide_msg']) && $val['hide_msg']==1) {
                    continue;
                }
                $this->giftModel->updateUserGiftStatistics($val['user_id'], $val['gift_id'], $val['gift_num'], $val['from_user_id']);
            }
        } catch (\Exception $e) {
            write_log('error_sendGift', 'handleUserGiftStatistics', ['streamList'=>$streamList, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
            return false;
        }
    }
    //主播收礼排行榜
    protected function handleAnchorAcceptGiftRank($streamList) {
        try {
            $ymd = date('Ymd');
            foreach($streamList as $val) {
                $giftPrice = $val['base_gift_price']*$val['gift_num'];
                if(in_array($val['gift_type'],[4,5,9])){
                    $giftPrice = 0;
                }
                if($giftPrice <= 0) {
                    continue;
                }
                //收礼用户是否是主播
                $unionInfo = $this->unionModel->getUserUnionInfo($val['user_id']);
                if(empty($unionInfo)) {
                    continue;
                }

                //主播收礼实时榜单
                $cacheKey = $this->anchorAcceptGiftTimeRankKey.$val['user_id'];
                Redis::zincrby($cacheKey, $giftPrice, $val['from_user_id']);
                Redis::expire($cacheKey, 86400*300);

                //主播收礼每日榜单
                $cacheKey = $this->anchorAcceptGiftDayRankKey.$val['user_id'].':'.$ymd;
                Redis::zincrby($cacheKey, $giftPrice, $val['from_user_id']);
                Redis::expire($cacheKey, 86400*7);
            }
        } catch (\Exception $e) {
            write_log('error_sendGift', 'handleAnchorAcceptGiftRank 主播收礼排行榜', ['streamList'=>$streamList, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
            return false;
        }
    }

    /**
     * 用户房间banner
     */
    public function handleUserRoomBanner($body) {
        $now = time();

        do {
            if(empty($body['type']) || empty($body['user_ids'])) {
                break;
            }
            $type = $body['type'];
            $userIds = $body['user_ids'];
            foreach($userIds as $userId) {
                //用户所在房间
                $roomId = $this->roomUserModel->get_user_cur_room($userId);
                if(empty($roomId)) {
                    continue;
                }

                $oldIds = Redis::get($this->userBannerKey.$userId.':3');
                if(!empty($oldIds)) {
                    $data = $this->adModel->get_banner(3, $userId);
                    if(!empty($data)) {
                        $ids = array_column($data, 'id');
                        sort($ids);
                        $ids = implode(',', $ids);
                        if($oldIds === $ids) {
                            continue;
                        }
                    }
                }

                //发送通知
                $this->msgService->roomBannerMsg($roomId, $userId);
            }

        } while (false);
    }

    //根据礼物ID获取礼物类型
    public function getGiftTypeByGiftId($giftId)
    {
        $giftInfo = $this->giftModel->getGift(['gift_id'=>$giftId],['gift_id', 'name', 'image', 'price', 'gift_type', 'classification', 'ext_data', 'wealth_num','hot_num','need_wealth_rank']);
        if(empty($giftInfo)) {
            return [];
        }

        return $giftInfo;
    }
    public function getStreamList($limit)
    {

        $StreamList=$this->giftModel->getStreamList($limit);
        if(empty($StreamList)){
            $result = [
                'code' => Hint::ERROR,
                'message' => '',
                'data' => [],
            ];
        }
        $result['code'] = Hint::SUCCESS;
        $result['message'] = '赠送礼物列表';
        $result['data'] = $StreamList;
        return $result;
    }

    public function batchNewLuckGiftHandle() {
        // 已处理gift_stream id
        $maxIdKey = $this->treatedLuckGiftStreamMaxId;
        $maxId = Redis::get($maxIdKey) ?: 0;

        $list = $this->giftModel->getUntreatedLuckGiftStream($maxId);
        $streamData = [];
        $streamSet = [];
        if ($list) {

            foreach ($list as $k => $v) {
                if ($v['id'] > $maxId) {
                    $maxId = $v['id'];
                }

                $streamKey = sprintf('%s-%s-%s-%s', $v['from_user_id'], $v['user_id'], $v['gift_id'], $v['room_id']);

                if (!isset($streamData[$streamKey])) {
                    $streamData[$streamKey] = $v;
                } else {
                    $streamData[$streamKey]['gift_num'] = bcadd($streamData[$streamKey]['gift_num'], $v['gift_num']);
                }

            }

            Redis::set($maxIdKey, $maxId);

            try {
                foreach ($streamData as $key => $value) {
                    unset($value['id']);
                    $streamId = $this->giftModel->addStream($value);
                    $value['stream_id'] = $streamId;
                    $value['base_gift_price'] = bcmul($value['gift_price'], 100);
                    $value['wealth_num'] = 0;
                    $streamList = [$value];

                    $keyArr = explode('-', $key);
                    $fromUserId = $keyArr[0];
                    $roomId = $keyArr[3];
//                    write_log('luck-gift', 'aa' , ['fromUserId' => $fromUserId, 'roomId' => $roomId, 'value' => $value]);

                    $this->handleNewLuckGiftSendMsg(1, $roomId, $fromUserId, $streamList);

                    //金币
                    $this->handleKkBalance($streamList, $roomId, []);

                    //MQ
                    $this->handleMq(1, $streamList);

                    //房间流水
                    $this->handleRoomWealthBalance($streamList, 1);
                    //财富值
                    $this->handleWealthBalance($streamList);
                    //魅力值
                    $this->handleCharmBalance($streamList);

                    //主播收礼排行榜
                    $this->handleAnchorAcceptGiftRank($streamList);

                    //用户礼物数量统计
                    $this->handleUserGiftStatistics($streamList);

                }

            } catch (\Exception $e) {
                write_log('error_luckGift', 'batchNewLuckGiftHandle', ['list' => $list, 'msg'=>$e->getMessage(), 'line'=>$e->getLine()]);
            }

        }

        unset($list);
        unset($streamData);

        sleep(5);
    }
}
